typescript 打字稿。参考错误:需要未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41790590/
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
Typescript. ReferenceError: require is not defined
提问by Michael Ritter
I read official docfor TypeScript, and I copy code from there.
我阅读了 TypeScript 的官方文档,并从那里复制了代码。
I install commonjs and requerejs.
我安装了 commonjs 和 requerejs。
"devDependencies": {
...
"commonjs": "latest",
"requirejs": "latest"
}
But I get a error in the browser:
但是我在浏览器中收到错误消息:
ReferenceError: require is not defined
It is index.html:
它是 index.html:
<!DOCTYPE html>
<body>
<script src="main.js"></script>
</body>
It is main.js after compiling:
编译后就是main.js:
"use strict";
var core_1 = require("./some_dir/some_file");
window.onload = function () {
var some = new some_file_1.SomeClass();
};
回答by Michael Ritter
Browsers don't have a understanding of modules (yet). That means while require() works if you execute it in node only, browsers don't know what to do with it.
浏览器(目前)还不了解模块。这意味着虽然 require() 仅在节点中执行才能工作,但浏览器不知道如何处理它。
There are 2 main methods of fixing this:
有两种主要的方法来解决这个问题:
- Remove the
exports/require
statements and include every single js file (in correct dependency order) into your html file (as script tags). They will all have the same scope and will work as if there was just one large concatenated file. This solution is pretty bad tho as it destroys scoping, doesn't really work with modules you got with npm and has bad loading times, as it has to fetch multiple js files from the server. - Use a resource bundler like
webpack
. Webpack will look at all dependant files starting from yourmain.js
file and bundle and compress them down into a single small.js
file. This also works for external dependencies (npm). All you have to do then is to include that singlebundle.js
file into the html.
- 删除
exports/require
语句并将每个单独的 js 文件(以正确的依赖顺序)包含到您的 html 文件中(作为脚本标签)。它们都具有相同的作用域,并且就像只有一个大的串联文件一样工作。这个解决方案非常糟糕,因为它破坏了范围,并不能真正处理你使用 npm 获得的模块,并且加载时间很短,因为它必须从服务器获取多个 js 文件。 - 使用像
webpack
. Webpack 会从你的main.js
文件和包开始查看所有依赖文件,并将它们压缩成一个小.js
文件。这也适用于外部依赖项 (npm)。您所要做的就是将该单个bundle.js
文件包含到 html 中。