Подтвердить что ты не робот

Экспортировать класс как Node.js модуль в TypeScript

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

export class ClassName { }

и ряд

export function functionName () { }

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

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

Есть ли способ сделать это с помощью синтаксиса экспорта TypeScript?

4b9b3361

Ответ 1

Вы можете сделать это довольно просто в TypeScript 0.9.0:

class ClassName { 
    functionName () { }
}

export = ClassName;

Ответ 2

Вот как я экспортирую модули CommonJS (Node.js) с помощью TypeScript:

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."