React Native启用Hermes引擎国际化安卓闪退问题

536 阅读1分钟

React Native 0.70已经默认启用Hermes引擎了,如果你的App需要做国际化可能在安卓平台会遇到闪退报错。

Android平台以往在用JSC引擎的时候,都会单独给整个Intl打polyfill,再换成Hermes引擎后则自带Intl实现,但是由于Hermes还未完全实现所有API,如果你使用了这部分API会出现闪退问题,所以这部分API需要打Polyfill。

还未支持的API

你会遇到怎样的问题

  1. 部分手机可能会直接闪退
  2. 部分手机可能会卡死在启动页(splash screen)
  3. 在Sentry中能监控到报错Cannot read property 'prototype' of undefined
  4. Intl.xxx找不到

如何解决

一, 安装Polyfill,此处你应该根据你所使用的API按需安装对应的包

yarn add @formatjs/intl-datetimeformat
yarn add @formatjs/intl-locale

二, 由于苹果端已经自带Intl,这个polyfill只需要打给安卓端,所以我们可以通过React Native的Native-specific extensions只引入安卓端。

创建一个polyfill的文件夹,在目录下建立两个文件index.ts index.android.ts,其中index.ts保持空文件,index.android.ts映入我们的polyfill

// index.android.ts

import "@formatjs/intl-locale/polyfill";
import "@formatjs/intl-numberformat/polyfill";
import "@formatjs/intl-numberformat/locale-data/en";
import "@formatjs/intl-numberformat/locale-data/zh";
import "@formatjs/intl-pluralrules/polyfill";
import "@formatjs/intl-pluralrules/locale-data/en"; // locale-data for en
import "@formatjs/intl-pluralrules/locale-data/zh"; // locale-data for en

这里请根据你的项目需要引入对应的包

三,在App.tsx中引入polyfill,这样我们的polyfill就只会打在安卓端

// App.tsx

import "./polyfill"

references:
hermesengine.dev/docs/intl
formatjs.io/docs/polyfi…