13

我正在尝试找出将我的应用程序拆分为几个可供其他应用程序使用的 CommonJS 模块的最佳方法。

我有 5 个 TS 类,我想将它们捆绑为一个 CommonJS 模块。然后我打算将此模块发布到私有 NPM 存储库,以便其他应用程序可以使用它。理想情况下,我想用它打包相关的 *.d.ts 定义文件。

最好的方法是什么?我正在使用外部 TS 模块,但这些模块会为每个 TS 类生成一个单独的 CommonJS 模块。

4

2 回答 2

18

As far as i know typescript doesn't support combining external modules yet. From their wiki on codeplex:

TypeScript has a one-to-one correspondence between external module source files and their emitted JS files. One effect of this is that it's not possible to use the --out compiler switch to concatenate multiple external module source files into a single JavaScript file.

However, you can do a trick by using internal modules in typescript, since the tsc compiler has the ability to compile them into a single file, and then you can just add one more file with a module.exports directive for the whole namespace to make it a CommonJS module.

Here is a step by step example. Let's say you have the following internal modules split into three files:

Validation.ts:

module Validation {
    export interface StringValidator {
        isAcceptable(s: string): boolean;
    }
}

ZipCodeValidator.ts

/// <reference path="Validation.ts" />
module Validation {
    var numberRegexp = /^[0-9]+$/;
    export class ZipCodeValidator implements StringValidator {
        isAcceptable(s: string) {
            return s.length === 5 && numberRegexp.test(s);
        }
    }
}

LettersOnlyValidator.ts

/// <reference path="Validation.ts" />
module Validation {
    var lettersRegexp = /^[A-Za-z]+$/;
    export class LettersOnlyValidator implements StringValidator {
        isAcceptable(s: string) {
            return lettersRegexp.test(s);
        }
    }
}

If you compile these with with the --out parameter in the tsc compiler you can combine them into a single file. However, that doesn't make them a CommonJS module. To export them you use a trick to add one more ts file called ValidationExport.ts containing the export directive for the namespace:

var module: any = <any>module;
module.exports = Validation;

And then you can run the tsc command to compile everything to a single file called "validationmodule.js":

tsc --out validationmodule.js Validation.ts ZipCodeValidator.ts LettersOnlyValidator.ts ValidationExport.ts

The output is a CommonJS module you can use in Node.js:

var Validation = require("./validationmodule");

var zipCodeValidator = new Validation.ZipCodeValidator();
var lettersOnylValidator = new Validation.LettersOnlyValidator();

console.log(zipCodeValidator.isAcceptable("16211"));
console.log(lettersOnylValidator.isAcceptable("5555"));
于 2014-10-29T15:04:34.517 回答
1

每个文件有一个单独的 CommonJS 模块是完全合适的。TypeScript 中的所有require调用都将转换为requireJavaScript 中的 CommonJS 调用,并.d.ts在此过程中提取文件。(如果你正在做一些愚蠢的事情,比如require在你的源目录之外添加类......停止。)

如果您打算在其他应用程序中使用此 NPM 包,则只需要考虑打包步骤,在这种情况下,请查看Browserify

于 2014-10-30T14:15:02.580 回答