TypeScript - 模块在运行时未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15451626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:48:38  来源:igfitidea点击:

TypeScript - Module is undefined at runtime

javascriptvisual-studio-2012typescript

提问by gipouf

I dont understand what i'm doing wrong. I've create a TypeScript project in VS2012, and created a file named "Vector.ts", in a sub-directory named "Physics":

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

// Module
module Physics {

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

}

Also, I have the following app.ts file:

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

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

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

The project is successfully compiled, but when i launch it, i get the following exception:

该项目已成功编译,但是当我启动它时,出现以下异常:

0x800a1391 - JavaScript runtime error: 'Physics' is undefined

0x800a1391 - JavaScript 运行时错误:'Physics' 未定义

I don't understand what am i doing wrong...

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

Thanks.

谢谢。

采纳答案by Jude Fisher

If you are using AMD style modules with a module loader such as Require.Js, you need an import statement. See Steve's accepted answer here: https://stackoverflow.com/a/14919495/1014822Your code will look something like:

如果您将 AMD 风格的模块与模块加载器(例如 Require.Js)一起使用,则需要一个 import 语句。在此处查看史蒂夫接受的答案:https: //stackoverflow.com/a/14919495/1014822您的代码将类似于:

import Physics = module("Physics/Vector");

var vector = new Physics.Vector(6);

... and you won't need this: /// <reference path="Physics/Vector.ts" />

......你不需要这个: /// <reference path="Physics/Vector.ts" />

If you are not using a module loader, you just need to make sure you include your Vector.jsoutput file somewhere in your html page, and make sure it loads before your app file. In this case, you use /// <reference path="Physics/Vector.ts" />to tell TS where to find your module for intellisense etc. to work.

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

回答by Serj Sagan

Just for completeness, if you're using Systemthen you'd use the importfunction:

只是为了完整性,如果您正在使用,System那么您将使用importfunction

System.import("Physics/Vector");

If you're doing this for Angular 2then you'd want to do this before your bootstrapimport

如果你这样做,Angular 2那么你会想在你之前这样做bootstrapimport