Javascript 在TypeScript中将类导出为Node.js模块
我熟悉TypeScript中的Javascript 在TypeScript中将类导出为Node.js模块,javascript,node.js,typescript,amd,Javascript,Node.js,Typescript,Amd,我熟悉TypeScript中的export关键字,以及使用TypeScript从节点模块导出内容的两种规范方法(当然,也可以使用TypeScript模块,但它们与我所寻找的更为不同): 以及一系列 export function functionName () { } 但是,我通常编写模块的方式是,以便以后将其作为可实例化闭包导入: var ClassName = function () { }; ClassName.prototype.functionName = function () {
export
关键字,以及使用TypeScript从节点模块导出内容的两种规范方法(当然,也可以使用TypeScript模块,但它们与我所寻找的更为不同):
以及一系列
export function functionName () { }
但是,我通常编写模块的方式是,以便以后将其作为可实例化闭包导入:
var ClassName = function () { };
ClassName.prototype.functionName = function () { };
module.exports = ClassName;
有没有一种方法可以使用TypeScript导出语法来实现这一点?您可以在TypeScript 0.9.0中非常简单地实现这一点:
class ClassName {
functionName () { }
}
export = ClassName;
下面是我如何使用TypeScript导出CommonJS(Node.js)模块的: src/ts/user/user.ts
export default class User {
constructor(private name: string = 'John Doe',
private age: number = 99) {
}
}
import User from "./user/User";
export = {
user: {
User: User,
}
}
"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
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."
src/ts/index.ts
export default class User {
constructor(private name: string = 'John Doe',
private age: number = 99) {
}
}
import User from "./user/User";
export = {
user: {
User: User,
}
}
"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
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."
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(编译模块入口点)
dist/commonjs/user/user.js(编译用户类)
测试代码(test.js)
从类定义中删除
导出
,它就能正常工作。谢谢:)@Braedep是的,对不起,忘了:)该死,为什么我这么愚蠢。有一段时间我一直在使用带节点的AMD模块:facepalm: