M1 运行 react-native 项目遇到的问题

系统:11.2.3
Xcode:12.5


错误提示:xx.app/main.jsbundle does not exist. this must be a bug with

问题描述: Build Config 选择 release 的情况下,运行 appmain.jsbundle 的图片没有加载。打包时会提示 main.jsbundle does not exist 错误。但是在 debug 状态下却没有出现这个问题。
原因分析: 应该是 main.jsbundle 的加载路径出现了问题,在 Build Phases 中可以看到 Bundle React Native code and images 这一栏中:

export NODE_BINARY=node
../node_modules/react-native/scripts/react-native-xcode.sh

大概意思是通过 node 运行 react-native-xcode.sh 这个脚本来加载图片,但是由于 M1node 所在的路径与之前的都不一样,导致了 Xcode 在运行时无法正确使用 node 指令。
解决办法: 打开终端,输入:which node,得到一下路径:/opt/homebrew/bin/node
将这个路径添加到 Bundle React Native code and images

export PATH="$PATH:/opt/homebrew/bin"
export NODE_BINARY=node
../node_modules/react-native/scripts/react-native-xcode.sh

重新运行后,图片可以显示了,问题得到解决。


错误提示:cannot initialize a parameter of type 'NSArray> *' with an lvalue of type 'NSArray *__strong' NSArray *newModules = [self _initializeModules:modules withDispatchGroup:NULL lazilyDiscovered:YES];

问题描述: 从 GitHub 上看到,这是在 Xcode 12.5 才有的错误。
解决办法: 把报错的参数类型,按照提示修改为对应的类型即可。
NSArray> * 改为 NSArray *
如果有集成了 cocoapods 就比较方便,直接在 Podfile 添加以下代码:

post_install do |installer|
## Fix for XCode 12.5
  find_and_replace(
  "../node_modules/react-native/React/CxxBridge/RCTCxxBridge.mm",
  "_initializeModules:(NSArray> *)modules", 
  "_initializeModules:(NSArray *)modules")
  
  find_and_replace(
  "../node_modules/react-native/ReactCommon/turbomodule/core/platform/ios/RCTTurboModuleManager.mm",
  "RCTBridgeModuleNameForClass(module))", 
  "RCTBridgeModuleNameForClass(Class(module)))"
  )
end

def find_and_replace(dir, findstr, replacestr)
  Dir[dir].each do |name|
      text = File.read(name)
      replace = text.gsub(findstr,replacestr)
      if text != replace
          puts "Fix: " + name
          File.open(name, "w") { |file| file.puts replace }
          STDOUT.flush
      end
  end
  Dir[dir + '*/'].each(&method(:find_and_replace))
end

你可能感兴趣的:(M1 运行 react-native 项目遇到的问题)