前言

Expo 为如今的 React Native 开发提供了一个强大的平台,它简化了开发流程,同时也提供了丰富的功能。然而,随着应用规模的增长,打包体积也会相应增加,影响应用的加载速度和性能。为了优化应用的打包体积,Expo 提供了 EAS Build 服务,它可以帮助开发者自动构建优化后的 APK 或 IPA 包。

基础打包流程参考EAS Build文档

以下示例主要针对Android平台打包。

适用于旧版本的Android Gradle的打包

如果您的APK包太大,您可以尝试在android/app/build.gradle文件中添加以下配置:

1
2
3
4
5
6
7
8
9
10
11
android {

split{
abi {
enable true
reset()
include 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
universalApk false
}
}
}

采用Expo构建的新项目一半没有android目录,需要手动添加。

1
2
# Prebuild for Android
npx expo prebuild --platform android

适用于新版本的Android Gradle的打包

在新项目中Expo推荐使用expo-build-properties插件配置原生构建属性。

1
2
# Install expo-build-properties
npx expo install expo-build-properties

app.json文件中添加以下配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
{
"expo": {
"name": "My Lean App",
"slug": "my-lean-app",
// ... 其他配置
"plugins": [
[
"expo-build-properties",
{
"android": {
// 1. 移除 x86 架构,只保留主流 ARM 架构
"abiFilters": ["armeabi-v7a", "arm64-v8a"],
// 2. 开启代码压缩和混淆
"enableProguardInReleaseBuilds": true,
// 在 Release 构建中开启代码混淆和压缩,移除未使用的代码。
"enableProguardInReleaseBuilds": true,
// 让 Google Play 根据设备屏幕密度分发对应的资源,减小用户下载体积。
"enableSeparateBuildPerCPUArchitecture": false, // 通常设为 false,因为 aab 已经处理了这个问题
"enableDexingArtifactTransform": false // 对于新版Gradle,此项通常无需开启
},
"ios": {
"useFrameworks": "static", // 推荐使用静态链接以获得更好的性能和潜在的体积优化
// (可选) 如果不适配 iPad,明确关闭支持
"supportsTablet": false
}
}
]
]
}
}

其他方案,仅保留一个平台架构

open android\gradle.properties file:

1
2
# 只保留arm64-v8a架构
reactNativeArchitectures=arm64-v8a

android/app/build.gradle

1
2
3
4
5
6
7
buildTypes {
release {
minifyEnabled true
shrinkResources true
crunchPngs (findProperty('android.enablePngCrunchInReleaseBuilds')?.toBoolean() ?: true)
}
}

app.json

1
2
3
4
5
6
7
"android": {
"package": "com.muieay.diary",
"enableProguardInReleaseBuilds": true,
"enableShrinkResourcesInReleaseBuilds": true,
"enableSeparateBuildPerCPUArchitecture": true
},

构建命令

1
2
3
4
5
6
7
8
9
# 构建 Android 应用
eas build --platform android --profile production

# 构建 iOS 应用
eas build --platform ios --profile production

# 本地构建 Android 应用
eas build --profile production --platform android --local
eas build --profile production --platform android --local --clear-cache