【问题标题】:How can I make code generated by TypeScript using AMD modules, actually execute?如何使 TypeScript 使用 AMD 模块生成的代码实际执行?
【发布时间】:2016-09-15 01:59:16
【问题描述】:

我刚开始使用 TypeScript,我制作了两个文件 lib.ts 和 main.ts,并在编译期间选择了 AMD 模块。编译器生成一个带有定义的文件,但它实际上并没有调用任何函数来执行。 main.ts 文件的内容只是包装在一个模块中。 以下是文件:

lib.ts

export namespace Library {
    export class Write {
        constructor() {
            console.log("hello world");
        }
    }
}

main.ts

import {Library} from "./lib";
new Library.Write();

编译命令:

tsc main.ts --outFile out.js --module amd

out.js

define("lib", ["require", "exports"], function (require, exports) {
    "use strict";
    var Library;
    (function (Library) {
        var Write = (function () {
            function Write() {
                console.log("hello world");
            }
            return Write;
        }());
        Library.Write = Write;
    })(Library = exports.Library || (exports.Library = {}));
});
define("main", ["require", "exports", "lib"], function (require, exports, lib_1) {
    "use strict";
    new lib_1.Library.Write();
});

如何让编译器真正生成可执行的代码?文档没有帮助。

【问题讨论】:

    标签: typescript amd tsc typescript1.8


    【解决方案1】:

    不应使用选项--outFile。 AMD 格式必须与浏览器中的异步加载器 RequireJS 一起使用。 RequireJS 会按需加载多个生成的 JavaScript 文件。

    另外,您需要在浏览器中加载 RequireJS 运行时。 参见the documentation

    注意:关于代码export namespace,不建议混用命名空间和模块,见this answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      • 2015-12-27
      • 2021-02-16
      • 1970-01-01
      相关资源
      最近更新 更多