This question already has answers here:
TypeScript getting error TS2304: cannot find name ' require'

(23个答案)


2年前关闭。




我不久前注意到,每当我尝试启动我的应用程序时,我都会收到大量的Cannot find name 'require'Cannot find type definition file for 'node'以及一个Cannot find type definition for 'react-router'
我已经尝试过的一些解决方案是:

1)在我的tsconfig.json中添加一个types: ["node"],正如大家在下面看到的那样。

2)在我的package.json中添加@types/node,大家都可以在这里看到。

3)删除node_modules并重新yarn,无济于事。我还删除了yarn.lock,问题仍然存在。

4)添加typeRoots: ["node_modules/@types/node"],这似乎没有多大作用。
// Package.json
"devDependencies": {
    "@types/lodash": "^4.14.110",
    "@types/node": "^10.12.18",
    "@types/react": "16.3.12",
    "@types/react-dom": "15.5.0",
    "@types/react-router": "4.0.11",
    "babel-core": "6.26.3",
    "babel-loader": "7.1.5",
    "babel-preset-es2015": "6.24.1",
    "babel-preset-react": "6.24.1",
    "css-loader": "1.0.0",
    "extract-text-webpack-plugin": "2.0.0-beta.4",
    "html-webpack-plugin": "2.24.1",
    "react": "15.5.4",
    "react-dom": "15.5.4",
    "react-router-dom": "4.1.1",
    "rimraf": "2.6.2",
    "style-loader": "0.22.1",
    "ts-loader": "1.2.1",
    "typescript": "3.2.2",
    "url-loader": "1.0.1",
    "webpack": "2.2.0",
    "webpack-dev-server": "1.16.2"
  }

//tsconfig.json (at root level)
{
    "compilerOptions": {
    "baseUrl": "./",
    "target": "es2016",
    "pretty": true,
    "module": "commonjs",
    "sourceMap": true,
    "jsx": "preserve",
    "outDir": "./dist/",
    "noImplicitAny": false,
    "preserveConstEnums": true,
    "strict": true,
    "allowSyntheticDefaultImports": true,
    "types": ["node"],
    "paths": {
      "*": ["node_modules/@types/*", "*"]
    }
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules"
  ]
}

上面的tsconfig和package.json组合产生以下错误:
ERROR in ./src/index.tsx
(5,1): error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig.

ERROR in /Users/johnli/Documents/portfolio/tsconfig.json
error TS2688: Cannot find type definition file for 'node'.

我注意到的一些奇怪行为是,添加types: ["node"]会删除我的Cannot find type definition file for 'react-router',但不会删除node。添加react-router会对nodereact-router均产生错误,而完全删除types属性也会对nodereact-router均产生错误。

我想避免使用declare var require: any作为解决方案,因为这不能解决问题的核心以及更多的补丁。

一些有用的更多信息: Node 版本为11.6.0, yarn 版本为1.13.0
还有其他建议可以使它正常工作吗?除了我上面尝试过的解决方案外,我似乎找不到其他解决方案。如果需要,我还可以提供更多信息。谢谢大家!

最佳答案

运行

npm install @types/node --save-dev
并在tsconfig文件中添加:-
 {
  "compilerOptions": {
    "types": ["node"]
 }
}

关于javascript - 在Typescript/React应用中找不到 'node'的类型定义文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54232428/

10-16 19:43
查看更多