React项目转TypeScript时遇Cannot find module './App'错误求助
React项目转TypeScript后找不到.tsx模块的问题解决
问题背景
已通过命令yarn add typescript @types/node @types/react @types/react-dom @types/jest安装TypeScript相关依赖,将index.js和App.js转为index.tsx和App.tsx后,运行项目出现模块找不到错误,使用.js扩展名时一切正常。
错误信息
Error: Cannot find module './App' at webpackMissingModule (bundle.js:16:50) at ./src/index.tsx (bundle.js:16:130) at options.factory (react refresh:6:1) at __webpack_require__ (bootstrap:24:1) at startup:7:1 at startup:7:1
项目package.json配置
{ "name": "workout_generator", "version": "0.1.0", "private": true, "dependencies": { "@emotion/react": "^11.10.0", "@emotion/styled": "^11.10.0", "@headlessui/react": "^1.6.6", "@mui/material": "^5.9.3", "@testing-library/jest-dom": "^5.16.5", "@testing-library/react": "^13.3.0", "@testing-library/user-event": "^14.4.2", "@types/jest": "^28.1.6", "@types/node": "^18.6.4", "@types/react": "^18.0.15", "@types/react-dom": "^18.0.6", "react": "^18.2.0", "react-dom": "^18.2.0", "react-icons": "^4.4.0", "react-router-dom": "^6.3.0", "react-scripts": "5.0.1", "typescript": "^4.7.4", "web-vitals": "^2.1.4" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "devDependencies": { "autoprefixer": "^10.4.8", "postcss": "^8.4.14", "tailwindcss": "^3.1.8" } }
解决方案
生成/添加tsconfig.json文件:Create React App需要该配置文件识别TypeScript文件,运行以下命令生成:
yarn tsc --init或者手动创建
tsconfig.json,添加适配React 18+的基础配置:{ "compilerOptions": { "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "noFallthroughCasesInSwitch": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx" }, "include": ["src"] }检查导入语句:确保
index.tsx中导入App时,要么明确指定.tsx扩展名,要么确认webpack能自动解析:// 推荐写法或确保配置支持无扩展名解析 import App from './App.tsx'; // 或 import App from './App';重启开发服务器:修改文件扩展名后缓存可能导致识别异常,停止当前
yarn start进程,重新启动:yarn start
内容的提问来源于stack exchange,提问作者Johan
相关产品推荐
相关产品推荐

