【问题标题】:How to fix '0x800a1391 - JavaScript runtime error: 'require' is undefined'?如何修复'0x800a1391 - JavaScript 运行时错误:'require' 未定义'?
【发布时间】:2017-04-27 12:04:05
【问题描述】:

我是一名 C# 开发人员,几乎没有尝试学习 Typescript 的网络经验。我正在为这个错误消息敲我的头。

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

简而言之,我已经构建了一个包含 Typescript 代码的 Html 应用程序。我使用 VS2015 作为我的 IDE。除了我的项目中的 app.ts 和 index.html 之外,我还有 5 个 Typescript 文件,每个文件只包含一个类(这是我的 C# 遗产)。

在 app.ts 中,我尝试在 window.onload Javascript 事件中实例化一个类。在 window.onload 正上方,我尝试导入我的一个类。

import {ClassA} from "./ClassA.ts";

window.onload = () => {

    var cls = new ClassA();
    cls.doSomething();
};

当我尝试运行此代码时,我在 import 语句的问题中收到错误消息。凭借非常基本的 Typescript 知识,我尝试了:

  1. 将每个类导出为它自己的模块。没用。
  2. 在 app.ts 顶部添加以下路径。没用。

    ///<reference path="require.d.ts" />
    ///<reference path="jquery.d.ts" />
    ///<reference path="node.d.ts" />
    

我很确定这是一个没有 Typescript 经验的人犯的新手错误。有人知道如何解决这个问题吗?

谢谢

【问题讨论】:

  • 感谢@gile 的快速回答。由于我对 Web 开发还很陌生,所以我很难理解这篇文章中的答案。我是否放置了一个指向 requirejs 的&lt;script&gt; 标签?或者我是否将require.d.ts 作为评论包含在我拥有的 app.ts 中?你能理解这个答案吗?

标签: typescript


【解决方案1】:

如果您正在为 Web 构建,您要么需要使用其他工具来解析模块(webpack、browserify 等),要么不使用模块。

如果您使用编译器选项outFile"module": "none",您将获得一个没有模块的文件,可以直接在浏览器中运行。

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "module": "none",
    "outFile": "./lib/out.js"
  }
}

ClassA.ts(不导出)

class ClassA {
    // stuff
}

app.ts(不导入)

///<reference path="./ClassA.ts" />

window.onload = () => {

    var cls = new ClassA();
}

将转换为:

var ClassA = /** @class */ (function () {
    function ClassA() {
    }
    return ClassA;
}());
///<reference path="./ClassA.ts" />
window.onload = function () {
    var cls = new ClassA();
};

【讨论】:

    猜你喜欢
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多