React Native 运行-android 模拟器错误 "Could not get BatchedBridge, make sure your bundle is packaged correctly"

React Native run-android error in emulator "Could not get BatchedBridge, make sure your bundle is packaged correctly"

我正在使用 Android Studio Emulator 并根据 this doc 配置 react-native-web 支持。但是每当我 运行 npm run android 它得到以下错误:

“无法获取 BatchedBridge,请确保您的包已正确打包”

我尝试了很多解决方案,例如:

但是还没有解决办法。 metro终端也没有错误。

下面是我的package.json

{
  "name": "shipdemo",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start --reset-cache",
    "test": "jest",
    "lint": "eslint .",
    "web": "webpack serve -d source-map --mode development --config \"./web/webpack.config.js\" --inline --color --hot",
    "build:web": "webpack --mode production --config \"./web/webpack.config.js\" --hot"
  },
  "dependencies": {
    "react": "17.0.1",
    "react-dom": "^17.0.2",
    "react-native": "0.64.2",
    "react-native-web": "^0.16.5"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "@babel/runtime": "^7.12.5",
    "@react-native-community/eslint-config": "^2.0.0",
    "babel-jest": "^26.6.3",
    "babel-loader": "^8.2.2",
    "babel-plugin-module-resolver": "^4.1.0",
    "babel-plugin-react-native-web": "^0.16.5",
    "eslint": "7.14.0",
    "jest": "^26.6.3",
    "metro-react-native-babel-preset": "^0.64.0",
    "react-test-renderer": "17.0.1",
    "url-loader": "^4.1.1",
    "webpack": "^5.39.0",
    "webpack-cli": "^4.7.2",
    "webpack-dev-server": "^3.11.2"
  },
  "jest": {
    "preset": "react-native-web"
  }
}

更新:

启用Pause on Caught Exception后,我在开发工具中得到了下面的信息。

同时,现在metro也报错了

我有修复,但背后的原因,发布这个答案是为了增加解决方案的可见性,相当于 this commit

所以我删除了 .babelrc 文件并将模块解析器设置移动到 webpack 配置中,更新了 babel.config.js 现在 web 相关设置不会干扰应用程序相关的 babel 设置。

我也更新了the mentioned article


.babelrc:

<已删除>

babel.config.js:

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
};

web/webpack.config.js:

...
...
...

      // The 'metro-react-native-babel-preset' preset is recommended to match React Native's packager
      presets: ['module:metro-react-native-babel-preset'],
      // Re-write paths to import only the modules needed by the app
      plugins: [
        'react-native-web',
        [
          'module-resolver',
          {
            alias: {
              '^react-native$': 'react-native-web',
            },
          },
        ],
      ],
...
...
...