【问题标题】:TypeScript - Module is undefined at runtimeTypeScript - 模块在运行时未定义
【发布时间】:2013-03-16 16:23:49
【问题描述】:

我不明白我做错了什么。我在 VS2012 中创建了一个 TypeScript 项目,并在名为“Physics”的子目录中创建了一个名为“Vector.ts”的文件:

// Module
module Physics {

    // Class
    export class Vector {
        constructor(public x: number) { }
    }

}

另外,我有以下 app.ts 文件:

/// <reference path="Physics/Vector.ts" />

window.onload = () => {
    var vector = new Physics.Vector(6);
};

项目编译成功,但是当我启动它时,我得到以下异常:

0x800a1391 - JavaScript 运行时错误:“物理”未定义

我不明白我做错了什么......

谢谢。

【问题讨论】:

    标签: javascript visual-studio-2012 typescript


    【解决方案1】:

    如果您使用带有模块加载器(例如 Require.Js)的 AMD 样式模块,则需要导入语句。在此处查看史蒂夫接受的答案:https://stackoverflow.com/a/14919495/1014822 您的代码将类似于:

    import Physics = module("Physics/Vector");
    
    var vector = new Physics.Vector(6);
    

    ...你不需要这个:/// &lt;reference path="Physics/Vector.ts" /&gt;

    如果您没有使用模块加载器,您只需要确保在您的 html 页面中的某处包含您的 Vector.js 输出文件,并确保它在您的应用程序文件之前加载。在这种情况下,您使用/// &lt;reference path="Physics/Vector.ts" /&gt; 告诉 TS 在哪里可以找到您的模块,以便智能感知等工作。

    【讨论】:

    【解决方案2】:

    为了完整起见,如果您使用的是 System,那么您将使用 import function

    System.import("Physics/Vector");
    

    如果您是为 Angular 2 执行此操作,那么您希望在您的 bootstrap import 之前执行此操作

    【讨论】:

      猜你喜欢
      • 2021-08-07
      • 2014-10-05
      • 1970-01-01
      • 2017-09-29
      • 2018-11-05
      • 2021-10-27
      • 2015-02-10
      • 2020-12-08
      • 1970-01-01
      相关资源
      最近更新 更多