您可以像这样在 TypeScript 中导出单个类:
class Person {
private firstName: string;
private lastName: string;
constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
public getFullName() {
return `${this.firstName} ${this.lastName}`;
}
}
export = Person;
以下是它的使用方式:
var Person = require('./dist/commonjs/Person.js');
var homer = new Person('Homer', 'Simpson');
var name = homer.getFullName();
console.log(name); // Homer Simpson
完整地说,这是我的tsconfig.json(我使用的是 TypeScript v2.0.3):
{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"outDir": "dist/commonjs",
"rootDir": "src/ts",
"target": "es5"
},
"exclude": [
"dist",
"node_modules"
]
}