首页 > 解决方案 > React Native 在新初始化的应用程序上找不到模块 ./index

问题描述

我发出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 和它的模块,所以没有缓存问题,但是是什么阻止了 react native 甚至是它的第一眼?

标签: javascriptreactjsreact-native

解决方案


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

如果需要, Metro 服务器实例由runAndroid.jsfrom@react-native-community模块启动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()

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


推荐阅读