在 Typescript/React 应用程序中找不到“节点”的类型定义文件

joh*_*zli 11 javascript node.js typescript reactjs tsconfig

我发现不是很久以前,每当我尝试启动我的应用程序,我收到很多Cannot find name 'require'Cannot find type definition file for 'node'Cannot find type definition for 'react-router'

我已经尝试过的一些解决方案是:

1)types: ["node"]在我的 tsconfig.json 中添加一个,如下所示。

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

3)删除node_modules和reing,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"
  ]
}
Run Code Online (Sandbox Code Playgroud)

上述 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'.
Run Code Online (Sandbox Code Playgroud)

我注意到的一些奇怪行为是添加types: ["node"]将删除 myCannot find type definition file for 'react-router'但不会删除node. 添加react-router产生用于两个误差nodereact-router,以及去除所述types属性完全还产生两个错误nodereact-router

我想避免使用declare var require: any作为解决方案,因为这并不能解决问题的核心,更像是一个补丁。

更多信息应该有用:节点版本是11.6.0和纱线版本是1.13.0

还有其他建议可以让这个工作吗?除了我上面尝试过的解决方案之外,我似乎找不到任何其他解决方案。如果需要,我还可以提供更多信息。谢谢大家!

Shi*_*pta 20

npm install @types/node --save-dev
Run Code Online (Sandbox Code Playgroud)

并在 tsconfig 文件中添加:-

 {
  "compilerOptions": {
    "types": ["node"]
 }
Run Code Online (Sandbox Code Playgroud)

}