TypeScript 出现错误 TS2304:找不到名称“require”

TypeScript getting error TS2304: cannot find name ' require'

我正在尝试启动我的第一个 TypeScript 和 DefinitelyTyped Node.js 应用程序,但 运行 和 运行 出现了一些错误。

当我尝试转换一个简单的 TypeScript Node.js 页面时出现错误 "TS2304: Cannot find name '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.ts 文件的内容是:

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

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

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

生成的 .js 文件似乎工作正常,所以我可以忽略错误。但我很高兴知道为什么会出现此错误以及我做错了什么。

你可以

declare var require: any

或者,要获得更全面的支持,请使用 DefinitelyTyped's require.d.ts

此外,您可以尝试以下

而不是 var mongoose = require('mongoose')
import mongoose from 'mongoose' // or
import mongoose = require('mongoose')

而不是:

'use strict';

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

尝试:

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

'use strict';

即先参考路径。

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

tsd install node --save

adds/updates 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[];
}

我拍了 to add declare var require: any; and made it into a generic solution that works for all .ts files generically by using the preprocess-loader:

  1. 安装预处理器加载器:

    npm install preprocessor-loader
    
  2. 将加载程序添加到您的 webpack.config.js(我正在使用 ts-loader 处理 TypeScript 源):

    module: {
        loaders: [{
            test: /\.tsx?$/,
            loader: 'ts-loader!preprocessor?file&config=preprocess-ts.json'
        }]
    }
  1. 添加将解决方法添加到每个源的配置:
{
    "line": false,
    "file": true,
    "callbacks": [{
        "fileName": "all",
        "scope": "source",
        "callback": "(function shimRequire(source, fileName) { return 'declare var require: any;' + source; })"
    }]
}

您可以用同样的方法添加更强大的 require.d.ts,但 declare var require: any; 在我的情况下就足够了。

注意,there's a bug in preprocessor 1.0.5,它会截断最后一行,所以只要确保你在末尾有一个额外的行 space return 就可以了。

快速而肮脏

如果您只有一个文件使用 require,或者您这样做是为了演示目的,您可以在 TypeScript 文件的顶部定义 require。

declare var require: any

打字稿2.x

如果您使用的是 TypeScript 2.x,则不再需要安装 Typings 或 Definitely Typed。只需安装以下软件包。

npm install @types/node --save-dev

The Future of Declaration Files (6/15/2016)

Tools like Typings and tsd will continue to work, and we’ll be working alongside those communities to ensure a smooth transition.

验证或编辑您的 src/tsconfig.app.json 使其包含以下内容:

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

确保是 src 文件夹中的文件,而不是根应用程序文件夹中的文件。

默认情况下,@types 下的任何包都已包含在您的构建中除非您指定了这些选项之一。 Read more

打字稿1.x

使用类型(DefinitelyTyped 的替代品)您可以直接从 GitHub 存储库指定定义。

安装打字

npm install typings -g --save-dev

从 DefinitelyType 的 repo 安装 requireJS 类型定义

typings install dt~node --save --global

Webpack

如果您使用 Webpack 作为构建工具,您可以包含 Webpack 类型。

npm install --save-dev @types/webpack-env

compilerOptions 下使用以下内容更新您的 tsconfig.json

"types": [
      "webpack-env"
    ]

这允许您执行 require.ensure 和其他 Webpack 特定功能。

Angular CLI

使用 CLI,您可以按照上面的 Webpack 步骤将“类型”块添加到您的 tsconfig.app.json

或者,您可以使用预装的 node 类型。请记住,这将在您的客户端代码中包含实际上不可用的其他类型。

"compilerOptions": {
    // other options
    "types": [
      "node"
    ]
  }

我也一直在为这个问题苦苦挣扎。我相信这适用于所有 release candidates aka rc 但我没有测试。对于 @angular rc.2 它运行良好。

  1. package.json
  2. 中添加 core-js 作为 npm 依赖项
  3. 运行 typings install core-js --save
  4. 删除 package.json 中出现的所有 "es6-shim" 次。你不再需要它了。

干杯!

  1. 您是否指定了使用哪个模块来转译代码?
    tsc --target es5 --module commonjs script.ts
    您必须这样做才能让转译器知道您正在编译 NodeJS 代码。 Docs.

  2. 您还必须安装 mongoose 定义
    tsd install mongoose --save

  3. 不要使用var来声明变量(除非必要,这种情况非常罕见),请改用letLearn more about that

对于 TypeScript 2.x,现在有两个步骤:

  1. 安装定义 require 的包。例如:

    npm install @types/node --save-dev
    
  2. 告诉 TypeScript 将其全局包含在 tsconfig.json:

    {
        "compilerOptions": {
            "types": ["node"]
        }
    }
    

仅当您需要访问全局可用的函数(例如 require)时,第二步才重要。对于大多数包,您应该只使用 import package from 'package' 模式。没有必要将每个包都包含在上面的 tsconfig.json 类型数组中。

我无法使用上述任何技巧来消除 'require' 错误。

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

您可以从以下位置下载最新版本的工具:

TypeScript for Visual Studio 2015

除了 cgatian 的回答,TypeScript 1.x

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

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

如果您可以编译代码,但是 Visual Studio 2015 标记 'require' 函数作为错误文本 cannot find name 'require' or 无法解析符号 'require',将 Visual Studio 2015 的 TypeScript 更新至最新版本(目前为 2.1.5)并将 ReSharper(如果您使用)更新至最低版本 2016.3.2.

这个烦人的问题困扰了我一段时间,找不到解决办法,但我终于这样解决了。

有时 tsconfig.json 中缺少 "jasmine" 可能会导致此错误。 (TypeScript 2.X)

所以添加

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

到您的 tsconfig.json 文件。

tsconfig.json中添加以下内容:

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

Electron + Angular 2/4 加法:

除了将 'node' 类型添加到 ts.config 各种文件之外,最终对我有用的是将下一个添加到 typings.d.ts 文件:

declare var window: Window;
interface Window {
  process: any;
  require: any;
}

请注意,我的案例是使用 Electron + Angular 2/4 开发的。我需要 window 全局的要求。

此答案与现代设置有关(TypeScript 2.x、Webpack > 2.x)

不需要安装@types/node(这是所有Node.js类型,与front-end代码无关,实际上使诸如 setTimout 不同的 return 值等事情变得复杂..

需要安装@types/webpack-env

npm i -D @types/webpack-env

它给出了 Webpack 具有的运行时签名(包括 requirerequire.ensure 等)

还要确保您的 tsconfig.json 文件没有设置 'types' 数组 -> 这将使其获取您的 node_modules/@types 文件夹中的所有类型定义。

如果您想限制类型搜索,您可以将 typeRoot 属性 设置为 node_modules/@types。

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

如果您在 .ts 文件中遇到这个问题,该文件只是为您提供一些常量值,那么您可以

rename your .ts file to .js file

而且错误不会再出现

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

中添加这一行
    "types": ["node"], // within compilerOptions

我还有另一个答案,它建立在所有之前描述 npm install @types/node 并包括 tsconfig.json / compilerOptions / types 中的 node 的答案之上。

在我的例子中,我有一个基础 tsConfig.json 和 Angular 应用程序中的一个单独的基础来扩展这个基础:

{
    "extends": "../../tsconfig.json",
    "compilerOptions": {
        "outDir": "../out-tsc/app",
        "types": []
 },

我的问题是这个 tsconfi.app.json 中的空 types - 它破坏了基本配置中的那个。

import * as mongoose from 'mongoose'

就我而言,这是一个超级愚蠢的问题,其中 src/tsconfig.app.json 覆盖了 tsconfig.json 设置。

所以,我在 tsconfig.json 中有这个:

    "types": [
      "node"
    ]

还有 src/tsconfig.app.json 中的这个:

    "types": []

我希望有人觉得这有帮助,因为这个错误让我头发花白。

对我来说,通过将 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 :)

如果您使用的是 Yarn v3 并在 VSCode 中看到此错误(找不到名称要求)或其他与节点相关的“找不到”错误,请确保您安装了 Yarn 的 VSCode sdk 插件并选择了 Typescript 的工作区版本。

安装sdks的命令:

yarn dlx @yarnpkg/sdks

要设置 Typescript 版本:

  1. Select 打字稿文件
  2. 按 Command + Shift + P
  3. 打字稿:Select打字稿版本
  • Select“使用工作区版本”

有关详细信息,请参阅 https://yarnpkg.com/getting-started/editor-sdks#vscode