node.js TypeScript 出现错误 TS2304:找不到名称“要求”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31173738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:56:34  来源:igfitidea点击:

TypeScript getting error TS2304: cannot find name ' require'

node.jstypescriptdefinitelytyped

提问by JerryKur

I am trying to get my first TypeScript and DefinitelyTyped Node.js application up and running, and running into some errors.

我正在尝试启动并运行我的第一个 TypeScript 和绝对类型的 Node.js 应用程序,但遇到了一些错误。

I am getting the error "TS2304: Cannot find name 'require' " when I attempt to transpile a simple TypeScript Node.js page. I have read through several other occurrences of this error on Stack Overflow, and I do not think I have similar issues. I am running at the shell prompt the command:

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

tsc movie.server.model.ts.

The contents of this file are:

这个文件的内容是:

'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';

The error is thrown on the var mongoose=require('mongoose')line.

错误被抛出就var mongoose=require('mongoose')行了。

The contents of the typings/tsd.d.ts file are:

Typings/tsd.d.ts 文件的内容是:

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

The .d.ts file references were placed in the appropriate folders and added to typings/tsd.d.ts by the commands:

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

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

The produced .js file seems to work fine, so I could ignore the error. But I would appreciate knowing why this error occurs and what I am doing wrong.

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

回答by cgatian

Quick and Dirty

又快又脏

If you just have one file using require, or you're doing this for demo purposes you can define require at the top of your TypeScript file.

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

declare var require: any

TypeScript 2.x

打字稿 2.x

If you are using TypeScript 2.x you no longer need to have Typings or Definitely Typed installed. Simply install the following package.

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

npm install @types/node --save-dev

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

声明文件的未来 (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.

Typings 和 tsd 等工具将继续发挥作用,我们将与这些社区一起工作以确保顺利过渡。

Verify or Edit your src/tsconfig.app.json so that it contains the following:

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

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

Make sure is the file in the srcfolder and no the one on the root app folder.

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

By default, any package under @types is already included in your build unlessyou've specified either of these options. Read more

默认情况下,@types 下的任何包都已包含在您的构建中,除非您指定了这些选项中的任何一个。 阅读更多

TypeScript 1.x

打字稿 1.x

Using typings (DefinitelyTyped's replacement) you can specify a definition directly from a GitHub repository.

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

Install typings

安装类型

npm install typings -g --save-dev

Install the requireJS type definition from DefinitelyType's repo

从绝对类型的 repo 安装 requireJS 类型定义

typings install dt~node --save --global

Webpack

网络包

If you are using Webpack as your build tool you can include the Webpack types.

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

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

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

Update your tsconfig.jsonwith the following under compilerOptions:

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

"types": [
      "webpack-env"
    ]

This allows you to do require.ensureand other Webpack specific functions.

这允许你做require.ensure和其他 Webpack 特定的功能。

Angular CLI

角 CLI

With CLI you can follow the Webpack step above and add the "types" block to your tsconfig.app.json.

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

Alternatively, you could use the preinstalled nodetypes. Keep in mind this will include additional types to your client-side code that are not really available.

或者,您可以使用预安装的node类型。请记住,这将包括您的客户端代码中不真正可用的其他类型。

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

回答by Jordan

For TypeScript 2.x, there are now two steps:

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

  1. Install a package that defines require. For example:

    npm install @types/node --save-dev
    
  2. Tell TypeScript to include it globally in tsconfig.json:

    {
        "compilerOptions": {
            "types": ["node"]
        }
    }
    
  1. 安装一个定义了require. 例如:

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

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

The second step is only important if you need access to globally available functions such as require. For most packages, you should just use the import package from 'package'pattern. There's no need to include every package in the tsconfig.json types array above.

仅当您需要访问全局可用的功能(例如require. 对于大多数包,您应该只使用import package from 'package'模式。不需要在上面的 tsconfig.json 类型数组中包含每个包。

回答by ???

You can

你可以

declare var require: any

Or, for more comprehensive support, use DefinitelyTyped's require.d.ts

或者,为了更全面的支持,请使用绝对类型的 require.d.ts

Also, instead of var mongoose = require('mongoose'), you could try the following

此外,var mongoose = require('mongoose')您可以尝试以下操作,而不是

import mongoose from 'mongoose' // or
import mongoose = require('mongoose')

回答by Nadav SInai

This answer relates to modern setups (TypeScript 2.x, Webpack> 2.x)

这个答案与现代设置有关(TypeScript 2.x,Webpack> 2.x)

You don'tneed to install @types/node (which is all of Node.js types and is irrelevant for front-end code, actually complicating things such as setTimout different return values, etc..

并不需要安装@类型/节点(这是所有类型的Node.js和是无关前端代码,实际上复杂的东西,如setTimout不同的返回值,等等。

You doneed to install @types/webpack-env

确实需要安装@types/webpack-env

npm i -D @types/webpack-env

npm i -D @types/webpack-env

which gives the runtime signatures that Webpack has (including require, require.ensure, etc.)

这使运行时的签名在的WebPack具有(包括requirerequire.ensure等)

Also make sure that your tsconfig.json file has no set 'types' array -> which will make it pickup all type definitions in your node_modules/@types folder.

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

If you want to restrict search of types you can set the typeRoot property to node_modules/@types.

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

回答by Hurricane

Instead of:

代替:

'use strict';

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

Try:

尝试:

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

'use strict';

i.e. reference path first.

即首先参考路径。

回答by Hearen

Just for reference, I am using Angular 7.1.4, TypeScript 3.1.6, and the only thing I need to do is to add this line in tsconfig.json:

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

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

回答by AlexStack

I found the solution was to use the TSD command:

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

tsd install node --save

Which adds/updates the typings/tsd.d.tsfile and that file contains all the type definitions that are required for a node application.

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

At the top of my file, I put a reference to the tsd.d.tslike this:

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

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

The require is defined like this as of January 2016:

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

declare var require: NodeRequire;

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

回答by h22a

In my case, it was a super stupid problem, where the src/tsconfig.app.jsonwas overriding the tsconfig.jsonsetting.

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

So, I had this in tsconfig.json:

所以,我有这个tsconfig.json

    "types": [
      "node"
    ]

And this one in src/tsconfig.app.json:

而这个在src/tsconfig.app.json

    "types": []

I hope someone finds this helpful, as this error was causing me gray hairs.

我希望有人觉得这有帮助,因为这个错误导致我白发。

回答by Benny Bottema

I took Peter Varga's answerto add declare var require: any;and made it into a generic solution that works for all .ts files generically by using the preprocess-loader:

我将Peter Varga 的答案添加declare var require: any;并使其成为通用解决方案,通过使用preprocess-loader一般适用于所有 .ts 文件:

  1. install preprocessor-loader:

    npm install preprocessor-loader
    
  2. add the loader to your webpack.config.js(I'm using ts-loaderfor processing TypeScript sources):

  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. Add the configuration that will add the workaround to every source:
  1. 添加将解决方法添加到每个源的配置:
{
    "line": false,
    "file": true,
    "callbacks": [{
        "fileName": "all",
        "scope": "source",
        "callback": "(function shimRequire(source, fileName) { return 'declare var require: any;' + source; })"
    }]
}


You can add the more robust require.d.tsthe same way, but declare var require: any;was sufficient in my situation.

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

Note, there's a bug in preprocessor 1.0.5, which cuts off the last line, so just make sure you have an extra line space return at the end and you'll be fine.

请注意,预处理器 1.0.5 中存在一个错误,它切断了最后一行,因此只需确保在末尾有一个额外的行空间返回,就可以了。

回答by Rupesh Kumar Tiwari

Make sure you have installed npm i @types/node

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