You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native新手求助:打包后Buffer缺失及AppRegistry报错

解决方案

处理 ReferenceError: Can't find variable: Buffer

  • 安装Buffer polyfill包:
    npm install buffer
    # 或使用 yarn: yarn add buffer
    
  • 配置Metro打包器:新建或修改项目根目录下的metro.config.js,添加如下内容:
    const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');
    
    module.exports = mergeConfig(getDefaultConfig(__dirname), {
      resolver: {
        extraNodeModules: {
          buffer: require.resolve('buffer'),
        },
      },
    });
    
  • 在项目入口文件(如index.js或App.js)顶部注入全局Buffer:
    import { Buffer } from 'buffer';
    global.Buffer = Buffer;
    

处理 Invariant Violation: Module AppRegistry is not a registered callable module 及白屏问题

  • 校验入口文件配置:
    1. 确认package.json的main字段指向正确入口(示例:"main": "index.js")
    2. 入口文件必须包含AppRegistry注册代码,示例:
      import { AppRegistry } from 'react-native';
      import App from './App';
      import { name as appName } from './app.json';
      
      AppRegistry.registerComponent(appName, () => App);
      
  • 彻底清除缓存:
    # 重置Metro缓存
    npx react-native start --reset-cache
    # iOS环境额外操作
    cd ios && pod deintegrate && pod install && cd ..
    # Android环境额外操作
    cd android && ./gradlew clean && cd ..
    
  • 修复依赖冲突:
    1. 删除node_modules、package-lock.json/yarn.lock
    2. 重新安装依赖:
      npm install
      # 或 yarn install
      
    3. 确保react与react-native版本匹配(如RN 0.72.x对应React 18.2.x)
  • 重新生成JS Bundle:
    # iOS
    npx react-native bundle --platform ios --dev false --entry-file index.js --bundle-output ios/main.jsbundle --assets-dest ios
    # Android
    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
    

内容的提问来源于stack exchange,提问作者Muneeb Nawaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 07:50:47