我试图在我的设备上第一次运行我的第一个React Native项目(Android 4.2.2)。

我得到:

无法从assets index.android.bundle中加载脚本

我使用的命令:

CD(项目目录) react-native开始 react-native运行android


当前回答

如果您正在物理设备上运行应用程序并得到此错误

unable to load script from assets index.android.bundle

试着运行命令:

adb reverse tcp:8081 tcp:8081

这对我很管用……

其他回答

即使在模拟器上运行,我也遇到了同样的问题。我做了一个快速的变通,这样我就可以拥有正常的开发工作流程。

private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
  @Override
  public boolean getUseDeveloperSupport() {
    // return true here to load JS from the packager
    // BuildConfig.DEBUG for me was set to false which meant it
    // it was always trying to load the assets from assets folder.
    return true;
  }

  @Override
  protected String getJSMainModuleName() {
    return "index";
  }
};

在尝试进行产品构建时,可能必须恢复更改。

我通过这个CMD来解析它:

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

IOS:

在终端中:

cd ios

使用:rm -r build删除build文件夹

再次运行:react-native Run -ios

或者,你可以打开Finder,导航到YOUR_PROJECT/ios并删除构建文件夹。

然后再次运行:react-native run-ios

为ANDROID:

在终端中:

cd android/app

使用:rm -r build删除build文件夹

再次运行:react-native Run -android

或者,你可以打开Finder,导航到YOUR_PROJECT/android/app并删除构建文件夹。

然后再次运行:react-native run-android

在命令之前使用NPX对我来说是有效的,命令就像下面这样。

npx react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

为什么我们使用npx,这里是npx和npm之间的区别?

我在学习React Native教程时也遇到过同样的问题(在Linux上开发,目标是Android)。

这个问题帮助我通过以下步骤解决了问题。

(在项目目录)mkdir android/app/src/main/assets React-native bundle——platform android——dev false——entry-file index.js——bundle-output android/app/src/main/assets/index.android。Bundle——assets-dest android/app/src/main/res react-native运行android

您可以通过将上述步骤放在包的脚本部分来自动化它们。Json是这样的:

"android-linux": "react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res && react-native run-android"

然后你可以每次都从你的命令行执行npm run android-linux。