create-react-app配置jsconfig后报Can't resolve 'App'错误
CRA项目配置src为导入根路径后编译报模块找不到的解决方法
报错复现信息
编译报错输出:
Failed to compile. Module not found: Error: Can't resolve 'App' in 'C:\Development_Projects\international-school-fe\src' ERROR in ./src/index.tsx 4:0-22 Module not found: Error: Can't resolve 'App' in 'C:\Development_Projects\international-school-fe\src' webpack compiled with 1 error
当前使用的jsconfig.json配置:
{ "compilerOptions": { "baseUrl": "src", "checkJs": true, "jsx": "react" }, "include": ["src"] }
src/index.tsx导入代码:
import App from "App"; import "common/styles/spacing/margin/index.css"; import "common/styles/spacing/padding/index.css"; import React from "react"; import ReactDOM from "react-dom"; import "./index.css"; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById("root") );
问题根源
- 你的项目是TypeScript模板创建的CRA项目(存在
.tsx后缀文件),jsconfig.json仅对纯JavaScript项目生效,TypeScript项目的路径解析配置需要写在根目录的tsconfig.json中,webpack构建时不会读取jsconfig里的路径规则,自然识别不到你配置的src根路径别名。 - 另外两个常见的配置不生效原因:一是配置文件放错位置,jsconfig/tsconfig必须和项目
package.json放在同一级根目录,不能放到src文件夹内;二是修改路径配置后没有重启开发服务,CRA的dev server不会热更新加载路径配置,改完必须重启才会生效。
修复操作
- 删除多余的jsconfig.json,打开项目根目录下的
tsconfig.json,在compilerOptions字段中加入"baseUrl": "src"配置,原有其他配置保持不变即可。 - 确认配置文件位置正确,和package.json同属项目根层级。
- 停掉当前运行的开发服务,重新执行启动命令(
npm start/yarn start),等待重新编译即可。
配置生效后,所有从src根目录开始的绝对路径导入都会被正常解析,不需要写相对路径前缀。
内容的提问来源于stack exchange,提问作者Huan Huynh
相关产品推荐
相关产品推荐

