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


当前回答

如果你正在使用Yarn v3,看到这个错误(不能找到name require)或其他节点相关的“不能找到”错误在VSCode中,确保你已经安装了Yarn的VSCode sdk插件,并选择了Typescript的工作空间版本。

安装sdk:

yarn dlx @yarnpkg/sdks

设置Typescript版本:

选择一个Typescript文件 按Command + Shift + P 类型Typescript:选择“Typescript版本”

选择“使用工作区版本”

详情见https://yarnpkg.com/getting-started/editor-sdks#vscode。

其他回答

在tsconfig.json中添加如下内容:

"typeRoots": [ "../node_modules/@types" ]

对我来说,它是通过向angular编译器选项中添加类型来解决的。

"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"strictInjectionParameters": true,
"types": [ "node" ]
}

由于批准的答案没有提到实际创建自己的类型文件的可能性,并将其导入,让我在下面添加它。

假设你使用npm作为包管理器,你可以:

npm i @types/node --save-dev

然后在你的tsconfig文件中:

tsconfig.json

"include": ["typings.d.ts"],

然后创建你的类型文件:

typings.d.ts

import 'node/globals'

完成,错误消失,享受TypeScript:)

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

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

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

TypeScript for Visual Studio 2015

有时tsconfig中会缺少“jasmine”。Json可能会导致此错误。(打印稿2. x)

所以添加

"types": [
  "node",
  "jasmine"
]

到你的tsconfig。json文件。