Visual Studio 2015 Update 2中的TypeScript模块 - “require”未定义 [英] TypeScript Modules in Visual Studio 2015 Update 2 - 'require' is undefined
问题描述
在Visual Studio 2015 Enterprise(安装了Update 2)中,我从模板创建了一个新的TypeScript-Project TypeScriptHTMLApp1(使用默认项目设置)。之后,我创建了新的TypeScript文件log.ts并从 https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#11.3 到新创建的文件。
In Visual Studio 2015 Enterprise (Update 2 installed) I've created a new TypeScript-Project TypeScriptHTMLApp1 from the Template (using default project settings). After that, I created the new TypeScript file log.ts and copied the example code from https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#11.3 to that newly created file.
// -------- log.ts --------
export function message(s: string) {
console.log(s);
}
接下来,我将以下代码行复制到应用程序的开头。 ts文件。
Next, I copied the following lines of code to the beginning of the app.ts files.
// -------- app.ts --------
import { message } from "./log";
message("hello");
class Greeter {
element: HTMLElement;
当我尝试在Internet Explorer中运行此项目时(从Microsoft Visual Studio IDE内部),我收到以下错误消息:
When I try to run this project in Internet Explorer (from inside the Microsoft visual Studio IDE), I receive the following error message:
Unhandled exception at line2, column 1 in http://localhost:20728/app.js
0x800a1391 - JavaScript runtime error: 'require' is undefined
推荐答案
您需要包含 requirejs 或使用 webpack 。 TypeScript提供模块语法并编译为 require
调用,但不提供运行时模块 loader 。您必须在页面中包含该脚本才能使脚本生效。
You need to include requirejs or bundle your scripts with webpack. TypeScript provides the module syntax and compiles down into require
calls, but does not provide a runtime module loader. You must include that in your page for the scripts to work.
在浏览器中,确保提供 - module
flag 并指定您正在使用的模块类型。对于您通过webpack运行的代码或 amd
/ umd <,这通常为
es6
/ code>使用requirejs的旧代码。
In the browser, make sure to provide the --module
flag and specify the type of module you're using. This will typically be es6
for code you're running through webpack or amd
/umd
for older code using requirejs.
如果你看看TS编译器的输出,你会看到
If you take a look at the TS compiler's output, you'll see that
import {foo} from './bar';
变为
define(["require", "exports"], function (require, exports) {
"use strict";
});
但请注意定义
和模块require
和exports
编译器未定义 。
but note that define
and the modules "require"
and "exports"
are not defined by the compiler.
如果您在节点环境中运行,则nodejs运行时为 commonjs模块加载。
If you're running in a node environment, the nodejs runtime provides the necessary functions for commonjs module loading.
这篇关于Visual Studio 2015 Update 2中的TypeScript模块 - “require”未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!