无法使用 TypeScript 和 Require.JS 引用对象

Cannot reference object using TypeScript and Require.JS

我有一个 TypeScript 项目。基本上我有一个名为 myId.ts:

的文件
export module MyModule {
    export class MyId {
        constructor() { ... }
        public compareTo(other: MyId): number { ... }
        public toString(): string { ... }
    }
}

我有一个 tsconfig.json:

{
    "compilerOptions": {
        "target": "es5",
        "noImplicitAny": true,
        "removeComments": false,
        "preserveConstEnums": true,
        "sourceMap": false,
        "module": "amd",
        "outDir": "./out"
    },
    "files": [
        "myId.ts"
    ]
}

我用这个命令编译这个东西:

tsc --project .

当前目录包含配置文件和源文件。

好吧,当编译一切正常时,我得到 out/myId.js:

define(["require", "exports"], function (require, exports) {
    var MyModule;
    (function (MyModule) {
        var MyId = (function () {
            function MyId() { ... }
            MyId.prototype.compareTo = function (other) { ... };
            MyId.prototype.toString = function () { ... };
        })();
        MyModule.MyId = MyId;
    })(MyModule = exports.MyModule || (exports.MyModule = {}));
});

引用 MyId

的问题

好吧,我想在网页中使用它并使用 JavaScript 调用它,所以按照 Require.JS guidelines,我创建了我的网页:

<html>
  <head>
    <meta charset="UTF-8">
    <title>EVT Example - Minimal</title>
    <script src="./require.js" type="text/javascript" data-main="./myId"></script>
  </head>
  <body></body>
</html>

但是,当我打开检查器(F12 工具)并尝试引用 MyModule.MyId 时,什么也找不到!如何引用我的类型?

一切正常

检查员告诉我myId.js实际上已成功加载。因此,Require.JS 没有加载脚本并不是问题。

怎么办?

when I open the inspector (F12 tools) and try referencing MyModule.MyId, nothing can be found! How can I reference my type

模块不是全局的,这是一件好事。所以如果你输入 MyModule.MyId 什么都不会发生。

如果你想在控制台上访问它 你可以把它放在 window 例如:

export module MyModule {
    export class MyId {
        constructor() { ... }
        public compareTo(other: MyId): number { ... }
        public toString(): string { ... }
    }
}
(window as any).MyModule = MyModule;

然后您可以在控制台中执行 MyModule.MyId。当然 只有一个全局 space 并且开始污染它是一个糟糕的主意(扼杀了模块化可维护的目的 JavaScript)。做测试也可以