Expo Bare Workflow 构建应用包大小较大的原因之一是因为 Expo 集成了各种第三方库和模块,而这些模块大部分在纯 React Native 应用中需手动添加。该问题可以通过使用代码分割来解决。
代码分割可通过使用 react-native-bundle-splitter 此类库实现。在使用 Expo Bare Workflow 构建应用时,必须在 app.json 文件中声明 "android": {"useNextNotificationsApi": true},并将 enableDangerousExperimentalLeanBuilds 设置为 false。然后在项目根目录下运行以下命令:
yarn add react-native-bundle-splitter --dev
在 App.js 文件中导入 BundleSplitter:
import { BundleSplitter } from 'react-native-bundle-splitter';
使用 BundleSplitter 组件包装应用根组件并传入拆分参数,例如:
<BundleSplitter
bundleSplitters={[
[/.*/, [/@fortawesome/, /@expo/, /i18n-js/]],
[/node_modules\/@babel\/runtime\//, [/@fortawesome/, /@expo/, /i18n-js/]],
]}
>
<App />
</BundleSplitter>
以上示例会将来自 @fortawesome、@expo 和 i18n-js 模块的所有代码拆分到单独的 bundle 中。
完成后重新构建应用即可看到应用包大小减小的效果。