[英]How to use a compiled TypeScript class in Javascript
Imagine I have this simple TypeScript class, Animal.ts
: 想象一下,我有这个简单的TypeScript类,
Animal.ts
:
export default class Animal {
constructor(public name : string) { }
}
With this tsconfig.json
file: 使用此
tsconfig.json
文件:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"strict": true
},
"files": [
"Animal"
]
}
How can I use the compiled version of this class (compiled by running tsc
) in a javascript file like so: 如何在javascript文件中使用此类的编译版本(通过运行
tsc
编译),如下所示:
var Animal = require("./Animal");
var newAnimal = new Animal();
Should I edit something in my tsconfig.json
file? 我应该在
tsconfig.json
文件中编辑一些东西吗? The error I get is: 我得到的错误是:
ReferenceError: Animal is not defined
ReferenceError:未定义Animal
As Shane van den Bogaard pointed out, the default
keyword in Animal.ts
needs to be omitted and : 随着巴蒂尔范登Bogaard指出的那样,
default
的关键字Animal.ts
需要被省略:
const { Animal } = require('./Animal');
should be used instead of 应该用来代替
var Animal = require('./Animal');
This way we can call the Animal
class and initialize an object by using 这样我们可以通过使用调用
Animal
类并初始化一个对象
const { Animal } = require('./Animal');
var newAnimal = new Animal("Clifford");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.