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

时间:2013-07-06 02:11:14

标签: javascript node.js typescript amd

我熟悉TypeScript中的export关键字,以及使用TypeScript从Node模块导出内容的两种规范方法(当然,也可以使用TypeScript模块,但它们甚至更远我正在寻找):

export class ClassName { }

和一系列

export function functionName () { }

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

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

我是否可以使用TypeScript导出语法执行此操作?

2 个答案:

答案 0 :(得分:18)

你可以在TypeScript 0.9.0中完成这些工作:

class ClassName { 
    functionName () { }
}

export = ClassName;

答案 1 :(得分:0)

以下是我使用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

测试代码(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."