React 17.0.2导入模块报Module not found找不到babel-loader错误如何解决
问题背景
你有两个文件:service服务文件和组件文件,导入service时触发编译报错,相关信息如下:
错误信息
Failed to compile. ./src/services/index.js Module not found: Can't resolve '/Users/andonmitev/Desktop/House of entertaiment/client/node_modules/react-scripts/node_modules/babel-loader/lib/index.js' in '/Users/andonmitev/Desktop/House of entertaiment/client'
相关代码
service文件(路径:client/src/services/index.js)
import axios from 'axios'; export default () => axios.get('http://localhost:4000/');
组件文件(路径:client/src/App.js)
import { useEffect } from 'react'; import getBase from './services'; function App() { useEffect(() => { (async () => { await getBase(); })(); }, []); return <h1>House of entertaiment</h1>; } export default App;
文件结构说明
service文件路径为client/src/services/index.js,组件文件路径为client/src/App.js,与services文件夹处于同级目录,编辑器导入自动补全、路径跳转功能均正常。
问题根因
你的导入路径、业务代码本身没有语法/逻辑错误,报错指向babel-loader模块缺失,属于项目依赖损坏/未完整安装的问题,和业务代码无关。
解决方案
按以下顺序操作即可:
- 第一步:停止当前运行的React开发服务
- 第二步:删除项目根目录下的
node_modules文件夹,以及锁文件(package-lock.json/yarn.lock/pnpm-lock.yaml) - 第三步:清除包管理器缓存,根据你使用的工具执行对应命令:
- npm用户:
npm cache clean --force - yarn用户:
yarn cache clean - pnpm用户:
pnpm store prune
- npm用户:
- 第四步:重新安装全部依赖:
# npm npm install # yarn yarn install # pnpm pnpm install - 第五步:重启开发服务验证:
npm run start
异常兜底方案
如果执行以上步骤后仍然报错,可以尝试以下操作:
- 检查项目路径是否存在特殊字符、空格:你当前的项目路径包含
House of entertaiment带空格的目录名,部分打包工具对空格路径兼容不佳,可将文件夹重命名为不带空格的格式(如house-of-entertainment)后重试 - 单独重装react-scripts:
npm install react-scripts@latest --save
内容的提问来源于stack exchange,提问作者Andon Mitev
相关产品推荐
相关产品推荐

