React Native项目打包失败:assert模块无法解析问题求助
assert Hey there, let's break down why this error is happening and how to fix it!
问题原因
This bundling error occurs because React Native's Metro bundler doesn't include Node.js core modules (like assert) by default. The @jest/console module used in your project relies on assert, but Metro can't locate it in its module map. Reinstalling npm doesn't help here because the module itself isn't missing—Metro just doesn't know how to handle Node.js core modules out of the box.
解决方法
方法1: Use rn-nodeify to Add Missing Core Modules
Since you already have rn-nodeify in your dev dependencies, let's leverage it to fix the issue:
- Run this command in your project root to install the
assertmodule and patch your configuration:rn-nodeify --install assert --hack - Check if a
shim.jsfile was generated in your project root. If it exists, add this import at the very top of your app's entry file (usuallyindex.jsorApp.js):import './shim.js';
This shim file tells Metro how to resolve Node.js core modules.
方法2: Manually Configure Metro to Resolve Node Core Modules
If the first method doesn't work, you can explicitly configure Metro to recognize Node.js core modules:
- Install the
node-libs-react-nativepackage, which provides React Native-compatible versions of Node.js core modules:npm install node-libs-react-native --save-dev - Create or update your
metro.config.jsfile in the project root with this configuration:const { getDefaultConfig } = require('metro-config'); module.exports = (async () => { const { resolver: { sourceExts, assetExts } } = await getDefaultConfig(); return { resolver: { extraNodeModules: require('node-libs-react-native'), }, }; })(); - Restart the Metro bundler to apply the changes.
方法3: Check Jest and Metro Preset Compatibility
Your current Jest version (24.8.0) and Metro preset version (0.54.1) might have compatibility issues with your React Native version. If the above methods fail:
- Verify that your Jest and
metro-react-native-babel-presetversions match the recommended versions for your React Native release. For example, React Native 0.60+ typically works better with Jest 25+. - You can update these dependencies by running:
(Make sure to check React Native's official docs for version-specific recommendations.)npm install jest@latest babel-jest@latest metro-react-native-babel-preset@latest --save-dev
内容的提问来源于stack exchange,提问作者Mayar Ahmed

