React项目Ubuntu执行npm start报错导入文件超出src目录如何解决
报错修复步骤
该报错本质是CRA内置的
ModuleScopePlugin限制了仅允许导入src目录内的模块,Ubuntu严格的路径解析规则会触发嵌套node_modules内@babel/runtime的导入限制,Windows路径解析逻辑宽松所以运行正常。仅替换babel-preset-react-app-webpack-5未生效是因为没有同步移除导入路径限制。
第一步:移除src目录导入限制
分两种项目场景处理:
已执行npm run eject暴露配置的项目
- 打开
config/webpack.config.js文件 - 注释/删除
ModuleScopePlugin的引入和实例化代码:
// 注释掉依赖引入行 // const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin'); // 在plugins数组中注释掉对应插件实例 // new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
未执行eject的项目
- 安装配置依赖:
npm install -D react-app-rewired customize-cra - 项目根目录新建
config-overrides.js文件,写入如下配置:
const { override, removeModuleScopePlugin } = require('customize-cra'); module.exports = override( removeModuleScopePlugin() );
- 修改
package.json的scripts配置,把原有的react-scripts替换为react-app-rewired:
"scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test" }
第二步:修正babel runtime导入配置
- 安装runtime依赖避免嵌套node_modules寻址异常:
npm install @babel/runtime @babel/runtime-corejs3 - 打开根目录的babel配置文件(.babelrc或babel.config.json),更新为如下内容:
{ "presets": ["babel-preset-react-app-webpack-5"], "plugins": [ ["@babel/plugin-transform-runtime", { "corejs": 3, "helpers": true, "regenerator": true, "useESModules": false }] ] }
第三步:清理缓存重启项目
rm -rf node_modules package-lock.json npm cache clean --force npm install npm start
内容的提问来源于stack exchange,提问作者JeremsB
相关产品推荐
相关产品推荐

