Visual Studio 2015 Update 2 中的 TypeScript 模块 - “require”未定义

2024-01-09

在 Visual Studio 2015 Enterprise(已安装更新 2)中,我从模板创建了一个新的 TypeScript-Project TypeScriptHTMLApp1(使用默认项目设置)。之后,我创建了新的 TypeScript 文件 log.ts 并复制了示例代码https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#11.3 https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#11.3到新创建的文件。

// -------- log.ts --------  
export function message(s: string) {  
    console.log(s);  
}

接下来,我将以下代码行复制到 app.ts 文件的开头。

// -------- app.ts --------  
import { message } from "./log";    
message("hello");

class Greeter {
    element: HTMLElement;

当我尝试在 Internet Explorer 中(从 Microsoft Visual Studio IDE 内部)运行此项目时,我收到以下错误消息:

Unhandled exception at line2, column 1 in http://localhost:20728/app.js
0x800a1391 - JavaScript runtime error: 'require' is undefined

您需要包括要求 http://requirejs.org/或将您的脚本与webpack http://webpack.github.io/。 TypeScript 提供模块语法并编译为require调用,但不提供运行时模块loader。您必须将其包含在页面中才能使脚本正常工作。

在浏览器中,确保提供--module flag https://www.typescriptlang.org/docs/handbook/compiler-options.html并指定您正在使用的模块的类型。这通常是es6对于您通过 webpack 运行的代码或amd/umd对于使用 requirejs 的旧代码。

如果你看一下 TS 编译器的输出,你会发现

import {foo} from './bar';

becomes

define(["require", "exports"], function (require, exports) {
    "use strict";
});

但请注意define和模块"require" and "exports" are not定义的由编译器.

如果您在节点环境中运行,则nodejs运行时提供了必要的功能通用模块 http://wiki.commonjs.org/wiki/Modules/1.1加载中。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Visual Studio 2015 Update 2 中的 TypeScript 模块 - “require”未定义 的相关文章

随机推荐