React Native 在新初始化的应用程序上找不到module ./index

IT技术 javascript reactjs react-native
2021-05-08 16:50:44

我发出react-native init MyAppreact-native run-android

Metro 服务器已启动,但是当电话从中请求数据时,它崩溃了

Error: Unable to resolve module `./index` from `\node_modules\react-native\scripts/.`: The module `./index` could not be found from `\node_modules\react-native\scripts/.`. Indeed, none of these files exist:

机器有新安装的节点、npm 和它的module,所以没有缓存问题,但是是什么阻止了本机react?

1个回答

解决方案 Github 参考:#23908(评论)

如果需要,Metro 服务器实例由runAndroid.jsfrom@react-native-communitymodule启动react-native run-android

问题在于工作目录,Metro 实例以错误的工作目录启动并且没有projectRoot传入launchPackager.bat

此问题有两个修复程序,仅应用以下之一

更新node_modules\react-native\scripts\launchPackager.bat file

@echo off
title Metro Bundler
call .packager.bat

:: delete this line
node "%~dp0..\cli.js" start 

:: Add this line
node "%~dp0..\cli.js" start --projectRoot ../../../ 

pause
exit

我们在这里通过projectRoot参数为 Metro 实例提供项目根路径

或者在\node_modules\@react-native-community\cli\build\commands\runAndroid\runAndroid.js编辑这个

const procConfig = {

    // delete this line    
    cwd: scriptsDir

    // add this line
    cwd: process.cwd()

};

我们正在启动带有工作目录的 Metro Server 到我们的项目根目录

有关更多信息,请参阅 中的startServerInNewWindow()函数\node_modules\@react-native-community\cli\build\commands\runAndroid\ranAndroid.js,它在 的第三个参数中传递react-native目录而不是项目根目录spawn()

成功了,希望对你也有帮助