【发布时间】:2023-03-24 18:30:01
【问题描述】:
不久前我注意到,每当我尝试启动我的应用程序时,我都会收到大量 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 并重新yarning,无济于事。我也删除了 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 会为node 和react-router 生成错误,完全删除types 属性也会为node 和react-router 生成错误。
我想避免使用declare var require: any 作为解决方案,因为这并不能解决问题的核心,而是一个补丁。
一些有用的信息:节点版本是11.6.0,纱线版本是1.13.0
还有什么其他建议可以让它工作吗?除了我上面尝试过的解决方案之外,我似乎找不到任何其他解决方案。如果需要,我还可以提供更多信息。谢谢大家!
【问题讨论】:
-
试试 npm install @types/node --save-dev
-
您没有在 tsconfig.json 的编译器选项中包含类型
-
types存在于tsconfig.json中,@types/node存在于package.json中,所以已经添加了。
-
我找到了解决方案;这是一个 webpack 解决方案;从 webpack 2.0.0 升级,以及所有插件恰好为我修复它。
-
我有这个问题。请让我知道我需要使用什么版本的 webpack 和插件?谢谢。
标签: javascript node.js reactjs typescript tsconfig