2013-07-06 77 views
10

我熟悉TypeScript中的export關鍵字,以及兩種使用TypeScript從Node模塊中導出事物的規範方法(當然,TypeScript模塊也可以使用,但它們甚至進一步從我正在尋找):在TypeScript中將類導出爲Node.js模塊

export class ClassName { } 

等一系列

export function functionName() { } 

不過,我平時寫我的模塊,讓他們在後面導入爲實例化封閉的方式,是:

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

有沒有一種方法可以使用TypeScript導出語法來做到這一點?

回答

16

你可以做到這一點很簡單的打字稿0.9.0:

class ClassName { 
    functionName() { } 
} 

export = ClassName; 
+0

從類中刪除定義了'export'和它完美的作品。謝謝:) – BraedenP

+0

@BraedenP耶對不起,忘了:) :) – basarat

+1

該死的,爲什麼我這麼愚蠢。我在節點上使用AMD模塊一段時間:facepalm: –

0

這裏是我出口CommonJS的(Node.js的)模塊,打字稿:

的src/TS /用戶/用戶.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.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."