执行npm update后TypeScript模块解析失败问题排查与解决
npm update后TypeScript解析模块异常的问题与解决
问题现象
- 项目原本运行正常,执行
npm update后出现异常:TypeScript无法解析包括react在内的已安装模块及用户自定义模块 - 在TypeScript JSX文件中执行
import * as React from 'react';时,IntelliSense提示TS2307错误:Cannot find module 'react' or its corresponding type declarations.ts(2307) - 执行
tsc编译时出现TS2686错误:error TS2686: 'React' refers to a UMD global, but the current file is a module. Consider adding an import instead,尽管代码中已添加导入语句
无效排查操作
- 重启VS Code
- 删除
node_modules及package-lock.json后重装依赖 - 降级/升级react、@types/react、TypeScript等依赖版本
- 安装所需VS Code扩展后,IntelliSense错误消失,但TS2686编译错误仍存在
最终解决
通过Stack Overflow相关问题的评论内容,修复了TS2686编译错误
相关环境及配置信息
VS Code版本信息
Version: 1.76.2 (user setup) Commit: ee2b180d582a7f601fa6ecfdad8d9fd269ab1884 Date: 2023-03-14T17:55:54.936Z Electron: 19.1.11 Chromium: 102.0.5005.196 Node.js: 16.14.2 V8: 10.2.154.26-electron.0 OS: Windows_NT x64 10.0.19044 Sandboxed: Yes
package.json配置
{ "name": "test-webpacking", "version": "0.1.0", "description": "", "main": "test.js", "typings": "test.d.ts", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "basic developer", "license": "ISC", "devDependencies": { "@types/react": "^18.0.28", "@types/react-dom": "^18.0.11", "css-loader": "^6.7.3", "style-loader": "^3.3.2", "webpack": "^5.76.2", "webpack-cli": "^4.10.0", "webpack-dev-server": "^4.13.1" }, "dependencies": { "html-webpack-plugin": "^5.5.0", "mini-css-extract-plugin": "^2.7.5", "prop-types": "^15.8.1", "react": "^18.2.0", "react-dom": "^18.2.0" } }
tsconfig.json配置
{ "compilerOptions": { "outDir":"src/js", "target": "es6", "lib": ["dom"], "jsx": "react", "module": "ES2021", "moduleResolution": "node", "isolatedModules": true, "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true } }
内容的提问来源于stack exchange,提问作者Gabe Fernandez
相关产品推荐
相关产品推荐

