我试图让我的第一个TypeScript和DefinitelyTyped Node.js应用程序启动和运行,并运行到一些错误。

当我试图编译一个简单的TypeScript Node.js页面时,我得到错误“TS2304:找不到名称'require'”。我已经阅读了Stack Overflow上发生的其他几次此错误,我不认为我有类似的问题。 我在shell提示符下运行命令:

tsc movie.server.model.ts.

这个文件的内容是:

'use strict';

/// <reference path="typings/tsd.d.ts" />

/*    movie.server.model.ts - definition of movie schema */

var mongoose = require('mongoose'),
Schema = mongoose.Schema;

var foo = 'test';

在var mongoose=require('mongoose')行上抛出错误。

typings/tsd.d. d的内容。Ts文件是:

/// <reference path="node/node.d.ts" />
/// <reference path="requirejs/require.d.ts" />

.d。Ts文件引用被放置在适当的文件夹中,并添加到typings/tsd.d。通过命令:

tsd install node --save
tsd install require --save

生成的.js文件似乎工作正常,所以我可以忽略这个错误。但我想知道为什么这个错误发生,我做错了什么。


当前回答

您是否指定了要使用什么模块来编译代码? TSC——target es5——module commonjs script.ts 您必须这样做才能让编译器知道您正在编译NodeJS代码。文档。 您还必须安装猫鼬定义 TSD安装猫鼬—保存 不要使用var来声明变量(除非必要,这是非常罕见的情况),而是使用let。了解更多

其他回答

使用上面的任何技巧都无法消除'require'错误。

但我发现问题是我的TypeScript工具的Visual Studio的旧版本(1.8.6.0)和最新版本(2.0.6.0)。

你可以从以下网站下载最新版本的工具:

TypeScript for Visual Studio 2015

您是否指定了要使用什么模块来编译代码? TSC——target es5——module commonjs script.ts 您必须这样做才能让编译器知道您正在编译NodeJS代码。文档。 您还必须安装猫鼬定义 TSD安装猫鼬—保存 不要使用var来声明变量(除非必要,这是非常罕见的情况),而是使用let。了解更多

而不是:

'use strict';

/// <reference path="typings/tsd.d.ts" />

试一试:

/// <reference path="typings/tsd.d.ts" />

'use strict';

即先参考路径。

我发现解决方案是使用TSD命令:

tsd install node --save

它添加/更新typings/tsd.d。Ts文件,该文件包含节点应用程序所需的所有类型定义。

在我的文件顶部,我像这样引用tsd.d.ts:

/// <reference path="../typings/tsd.d.ts" />

截至2016年1月,需求的定义如下:

declare var require: NodeRequire;

interface NodeModule {
    exports: any;
    require: NodeRequireFunction;
    id: string;
    filename: string;
    loaded: boolean;
    parent: any;
    children: any[];
}

除了cgatian的答案,对于TypeScript 1.x

如果仍然看到错误,请在编译器选项中特别提供index.d.ts。

"files": [
    "typings/index.d.ts"
]