对于已编译的 TypeScript 中的 "require is not defined" 错误,我该怎么办?

What can I do about a "require is not defined" error in compiled TypeScript?

我的应用程序中有三个 TypeScript 文件。当我构建时,它们编译得很好,Gulp 将它们放在正确的位置,并且应用程序崩溃,因为我得到:

ReferenceError: require is not defined

对于TS编译输出的三个JS文件中的每一个。现在我不能很好地分辨 tsc "do not use require",可以吗?

当我添加引用时

<reference path="~/wwwroot/js/system.src.js" />

到 gulpFile.js,然后 require 在该文件中工作,但在我的构建中是 运行,而不是在浏览器的运行时。如果我将它添加到编译的 JS 文件之一,它不起作用。

在加载应用程序之前,您需要将一些文件 "manually" 包含到您的 index.html 或您使用的任何内容(即 cshtml Razor 模板)中。它应该看起来像这样

<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->
<script src="~/lib/core-js/client/shim.min.js"></script>
<script src="~/lib/zone.js/dist/zone.js"></script>
<script src="~/lib/reflect-metadata/Reflect.js"></script>
<script src="~/lib/systemjs/dist/system.src.js"></script>

<!-- 2. Configure SystemJS -->
<script src="~/app/system.config.js" asp-append-version="true"></script>
<script>
  System.import('app').catch(function(err){ console.error(err); });
</script>

顺序很重要。这是 运行 应用程序所必需的。

如果您在 Visual Studio 中遇到错误,那么您可能缺少所需的 "typings"。

到现在为止,您需要安装 typings(从 nodejs 页面安装 nodejs 以使其在 shell/powershell/command 行中全局可用)然后 运行 npm install typings -g 来安装 typings 和切换到项目所在的文件夹和 运行 typings install dt~nodetypings install dt~jasminetypings install dt~core-js。这将在 typings 文件夹中安装输入文件。

对于 TypeScript 2.0,有一个更新的通过 npm 安装类型定义 w/o 打字的需要(参见 TypeScript 2.0 公告 here),通过 运行 宁以下命令: npm install -s @types/<nameofthelibrary>, 即 npm install -s @types/node, npm install -s @types/jasminenpm install -s @types/core-js.

require 方法在 node package/typings 中定义,如节点类型内 index.d.ts 文件中的 declare var require: NodeRequire; 所示。