[React Native]Tạo file APK release Android

Nếu bạn đã làm theo hướng dẫn trên document của React Native về việc tạo file apk cho app Android mà gặp lỗi "Ứng dụng bị dừng" thì dưới đây là giải pháp cho bạn.

Chạy lệnh sau để tạo folder assets trong android/app/src/main

mkdir android/app/src/main/assets

Nếu đã có folder assets, sẽ có lỗi

mkdir: android/app/src/main/assets: File exists

Chạy lệnh sau ở thư mục gốc của dự án để xoá bỏ file index.android.bundle đã có trong dự án.

rm android/app/src/main/assets/index.android.bundle

Nếu trong dự án không có file này, terminal sẽ báo lỗi:

rm: android/app/src/main/assets/index.android.bundle: No such file or directory

Tiếp tục chạy lệnh dưới đây để tạo file index.android.bundle

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

Chạy lệnh trên thành công, bạn sẽ nhận được kết quả bên dưới

Nếu bây giờ bạn chạy lệnh để tạo file .apk sẽ xảy ra lỗi Duplicate Resource

Mở thư mục gốc của dự án và tìm đến folder res theo đường dẫn [root]/android/app/src/main/res, sau đó xoá tất cả các folder được khoanh đỏ như hình bên dưới:

Từ thư mục gốc của dự án, chạy lệnh sau để vào folder android:

cd android

Chạy lệnh sau để tạo ra file app-release.apk:

./gradlew clean && ./gradlew assembleRelease

Nếu chạy thành công, bạn sẽ tìm thấy file app-release.apk trong thư mục [root]/android/app/build/output/apk/app-release.apk

Nếu gặp lỗi gì khác, hãy xoá folder node_modules, chạy yarn hoặc npm install và làm lại từ đầu. :v

Khi quá trình xây dựng của bạn thành công, từ thư mục gốc của dự án, chạy lệnh bên dưới cài đặt ứng dụng trên thiết bị của bạn.

npx react-native run-android --variant=release

Bonus:

File .aab có dung lượng nhẹ hơn file .apk(khoảng gần 1 nửa) nên thường dùng để upload lên Google Play Console. Nếu muốn tạo file này thì cần config 1 số thứ như link trên đầu bài viết đã nói và thay vì chạy ./gradlew clean && ./gradlew assembleRelease thì chạy lệnh sau để tạo file .aab.

./gradlew clean && ./gradlew bundleRelease

Nếu chạy thành công, bạn sẽ tìm thấy file app-release.aab trong thư mục [root]/android/app/build/output/aab/app-release.aab

File này không chạy trên thiết bị thật được, chỉ dùng để upload nên cần may mắn. :v

Bài viết được tham khảo từ nguồn: