以下是我如何使用TypeScript导出CommonJS (Node.js)模块的方法:
src/ts/user/User.ts
export default class User {
constructor(private name: string = 'John Doe',
private age: number = 99) {
}
}
src/ts/index.ts
import User from "./user/User";
export = {
user: {
User: User,
}
}
tsconfig.json
{
"compilerOptions": {
"declaration": true,
"lib": ["ES6"],
"module": "CommonJS",
"moduleResolution": "node",
"noEmitOnError": true,
"noImplicitAny": true,
"noImplicitReturns": true,
"outDir": "dist/commonjs",
"removeComments": true,
"rootDir": "src/ts",
"sourceMap": true,
"target": "ES6"
},
"exclude": [
"bower_components",
"dist/commonjs",
"node_modules"
]
}
dist/commonjs/index.js(编译后的模块入口点)
"use strict";
const User_1 = require("./user/User");
module.exports = {
user: {
User: User_1.default,
}
};
dist/commonjs/user/User.js (Compiled User class)
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class User {
constructor(name = 'John Doe', age = 72) {
this.name = name;
this.age = age;
}
}
exports.default = User;
测试代码(test.js)
const MyModule = require('./dist/commonjs/index');
const homer = new MyModule.user.User('Homer Simpson', 61);
console.log(`${homer.name} is ${homer.age} years old.`);
export
,它就可以完美地工作了。谢谢 :) - BraedenP