如果“需求”没有定义,我该怎么办?编译后的TypeScript错误

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

本文关键字:编译 错误 TypeScript 我该怎么办 需求 定义 如果      更新时间:2023-09-26

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

ReferenceError: require is not defined

对于TS编译输出的三个JS文件中的每一个。现在我不能很好地告诉tsc"不要用require",是吗?

当我添加引用

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

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

你需要包括一些文件"手动"到你的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"。

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

在TypeScript 2.0中,有一个通过npm安装类型定义的更新,而不需要类型(见TypeScript 2.0的公告),通过运行以下命令:npm install -s @types/<nameofthelibrary>,即npm install -s @types/node, npm install -s @types/jasminenpm install -s @types/core-js

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