React Native Metro Bundler无法加载脚本,多种尝试后仍未解决求助
解决React Native Metro Bundler无法正常工作的方案
检查并释放Metro默认端口
Metro默认使用8081端口,若被其他进程占用会导致异常。执行以下命令排查:# macOS/Linux lsof -i :8081 # Windows netstat -ano | findstr :8081找到占用端口的进程PID后,强制终止:
# macOS/Linux kill -9 <进程PID> # Windows taskkill /F /PID <进程PID>之后重新启动Metro:
npx react-native start重置Metro缓存
缓存损坏是常见诱因,直接带参数启动Metro重置缓存:npx react-native start --reset-cache也可手动删除项目下的
node_modules/.cache/metro文件夹,再重启Metro。验证Metro配置文件
确认项目根目录的metro.config.js配置无错误,基础配置示例如下,若有自定义规则需检查语法和路径:const {getDefaultConfig, mergeConfig} = require('@react-native/metro-config'); const config = {}; module.exports = mergeConfig(getDefaultConfig(__dirname), config);确保设备与Metro服务连通
若使用模拟器,执行端口转发命令确保设备能访问本地Metro:adb reverse tcp:8081 tcp:8081完成后在模拟器内摇一摇设备(或按Ctrl+M/Command+M),选择重新加载应用。
重新安装项目依赖
若以上方案无效,尝试重置依赖环境:# macOS/Linux rm -rf node_modules package-lock.json yarn.lock # Windows rmdir /s/q node_modules && del package-lock.json yarn.lock然后重新安装依赖:
npm install(或yarn install),再依次启动Metro和运行Android项目。
内容的提问来源于stack exchange,提问作者Leonardo Gustobia
相关产品推荐
相关产品推荐

