在 TypeScript 中将类导出为 Node.js 模块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17498979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Export class as Node.js module in TypeScript
提问by BraedenP
I'm familiar with the export
keyword in TypeScript, and two canonical ways of exporting things from Node modules using TypeScript (of course, the TypeScript modules can be used as well, but they are even further from what I'm looking for):
我熟悉export
TypeScript 中的关键字,以及两种使用 TypeScript 从 Node 模块导出事物的规范方法(当然,也可以使用 TypeScript 模块,但它们与我正在寻找的更远):
export class ClassName { }
and a series of
和一系列
export function functionName () { }
However, the way I usually write my modules, so that they are later imported as instantiable closures, is:
然而,我通常编写模块的方式是:
var ClassName = function () { };
ClassName.prototype.functionName = function () { };
module.exports = ClassName;
Is there a way I can do this using the TypeScript export syntax?
有没有办法使用 TypeScript 导出语法来做到这一点?
回答by basarat
You can do that quite simply in TypeScript 0.9.0 :
您可以在 TypeScript 0.9.0 中非常简单地做到这一点:
class ClassName {
functionName () { }
}
export = ClassName;
回答by Benny Neugebauer
Here is how I export CommonJS (Node.js) modules with TypeScript:
这是我使用 TypeScript 导出 CommonJS (Node.js) 模块的方法:
src/ts/user/User.ts
src/ts/user/User.ts
export default class User {
constructor(private name: string = 'John Doe',
private age: number = 99) {
}
}
src/ts/index.ts
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 (Compiled module entry point)
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 (Compiled User class)
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 code (test.js)
测试代码(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."