【问题标题】:Typescript compilation depends on order of files打字稿编译取决于文件的顺序
【发布时间】:2016-01-31 19:26:09
【问题描述】:

我正在开发打字稿库,我想在我的网络应用程序中使用它。

我想将所有库文件编译成单个 library.js 文件。

我尝试将 ts 编译器与 tsconfig.json 文件一起使用以及使用 gulp 任务进行编译,但在这两种情况下,输出文件中的类顺序都有问题。

生成的代码也有很多 IIFE

var MyLibrary;
(function (MyLibrary) {
.....
})(MyLibrary || (MyLibrary = {}));

我猜它应该只有一次,而不是每个班级,对吧?

我的 tsconfig.json:

{
  "compilerOptions": {
    "module": "amd",
    "noImplicitAny": false,
    "removeComments": true,
    "preserveConstEnums": true,
    "outFile": "dist/js/floor-map-designer.js",
    "sourceMap": true
  },
  "exclude": [
    "node_modules",
    "dist",
    "src/app.ts"
  ]
}

和 gulp 任务配置:

var tsProject = ts.createProject({
    declarationFiles: true,
    noExternalResolve: false,
    module: 'AMD',
    removeComments: true,
    outFile: "my-library.js",
    exclude: ["app.ts", "config.ts"]
});

var paths = {
    npm: './node_modules/',
    lib: "./lib/vendor/",
    tsSource: ['./src/MyLibrary/**/*.ts', "./lib/typings/tsd.d.ts"],
    tsOutput: "./dist/js/",
    tsDef: "./lib/typings/"
};

gulp.task('ts-compile', function () {
    var tsResult = gulp.src(paths.tsSource)
                    .pipe(ts(tsProject));

    return merge([
        tsResult.dts.pipe(gulp.dest(paths.tsDef)),
        tsResult.js.pipe(gulp.dest(paths.tsOutput))
    ]);
});

我记得上次我使用 TypeScript 创建自动生成的参考文件有很多

/// <reference path="...." 

并添加 /// &lt;ts:autoRef="referencesFile.ts"&gt; 到所有 .ts 文件。

但我注意到 TS 编译器不应该再依赖文件顺序,我的 IDE 也不再需要它,所以我想尽可能避免它。

我还注意到使用 --out 选项被认为是不好的(至少根据这个网站:https://github.com/TypeStrong/atom-typescript/blob/master/docs/out.md)但是如何替换它呢?

我正在使用 Typescript 1.7。

【问题讨论】:

    标签: javascript compilation typescript


    【解决方案1】:

    我还注意到使用 --out 选项被认为是不好的(至少根据这个网站:https://github.com/TypeStrong/atom-typescript/blob/master/docs/out.md)但是如何替换它呢?

    使用模块:https://basarat.gitbooks.io/typescript/content/docs/project/modules.html

    在你的情况下改变:

    module: 'AMD',
    removeComments: true,
    outFile: "my-library.js",
    

    module: 'amd',
    removeComments: true,
    

    并使用模块加载器(对于 AMD 来说,这将是 requirejs http://requirejs.org/

    【讨论】:

    • 好的,我试试。这是否意味着即使对于内部模块依赖项,我也必须添加导入?示例:A 类扩展 B - 我必须导入 B 吗?
    • 是的。如果你不这样做,那么你必须以与实际源断开连接的方式自己管理排序(例如 files array ,reference file hacks 等)
    • 感谢您的建议,我尝试使用 RequireJS 和 AMD 模块,但对我来说效果不佳。 RequireJS 在 Google Chrome 中似乎有很多错误(当开发者控制台打开时,它甚至不加载数据主文件)。而且我强烈希望将我的库连接到一个文件中。我想我可以使用 requireJS 加载该连接文件,但我不想加载每个类和接口。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-19
    • 1970-01-01
    • 2022-11-15
    相关资源
    最近更新 更多