2013-07-06 3 views
10

Я знаком с ключевым словом export в TypeScript и двумя каноническими способами экспорта объектов из модулей узла с использованием TypeScript (конечно, модули TypeScript также могут использоваться, но они которые еще дальше от того, что я ищу):Экспортный класс как модуль Node.js в TypeScript

export class ClassName { } 

и ряд

export function functionName() { } 

Однако, как я обычно пишу свои модули, так что позже они импортируются как инстанциируемое закрытие, is:

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/пользователя/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 

расстояние/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 

код 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." 
Смежные вопросы