我试图让我的第一个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文件似乎工作正常,所以我可以忽略这个错误。但我想知道为什么这个错误发生,我做错了什么。


当前回答

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

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

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

其他回答

如果你可以编译代码,但是Visual Studio 2015将'require'函数标记为错误文本无法找到名称'require'或无法解析符号'require',请将TypeScript for Visual Studio 2015更新到最新版本(目前为2.1.5),并将ReSharper(如果你使用它)更新到至少2016.3.2版本。

这个烦人的问题困扰了我一段时间,一直找不到解决方法,但我最终用这种方法解决了它。

仅供参考,我使用的是Angular 7.1.4, TypeScript 3.1.6,我唯一需要做的就是在tsconfig.json中添加这一行:

    "types": ["node"], // within compilerOptions

确保你已经安装了npm i @types/node

我发现解决方案是使用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[];
}
import * as mongoose from 'mongoose'