在TypeScript中将类导出为Node.js模块

我熟悉TypeScript中的export关键字,以及两种使用TypeScript从Node模块中导出事物的规范方法(当然,也可以使用TypeScript模块,但是它们比我所寻找的更进一步):

 export class ClassName { } 

和一系列

 export function functionName () { } 

但是,我通常写我的模块的方式,以便他们以后导入作为可实例化闭包,是:

 var ClassName = function () { }; ClassName.prototype.functionName = function () { }; module.exports = ClassName; 

有没有一种方法,我可以使用TypeScript导出语法来做到这一点?

       

网上收集的解决方案 "在TypeScript中将类导出为Node.js模块"

您可以在TypeScript 0.9.0中简单地做到这一点:

 class ClassName { functionName () { } } export = ClassName; 

下面是我如何使用TypeScript导出CommonJS(Node.js)模块:

SRC / TS /用户/ 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, } }; //# sourceMappingURL=index.js.map 

dist / commonjs / user / User.js(编译的用户类)

 "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; //# sourceMappingURL=User.js.map 

testing代码(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.`); // "Homer Simpson is 61 years old."