1. 程式人生 > >react-native ios打包上線 for mac

react-native ios打包上線 for mac

開發React Native的過程成,js程式碼和圖片資源執行在一個Debug Server上,每次更新程式碼之後只需要使用command+R鍵重新整理就可以看到程式碼的更改,這種方式對於除錯來說是非常方便的。
但當我們需要釋出App到App Store的時候就需要打包,使用離線的js程式碼和圖片。這就需要把JavaScript和圖片等資源打包成離線資源,在新增到Xcode中,然後一起釋出到App Strore中。
打包離線資源需要使用命令react-native bundle(注:文中使用的專案名稱為RNIos)

react-native bundle

  • --entry-file ,ios或者android入口的js名稱,比如index.ios.js

  • --platform ,平臺名稱(ios或者android)

  • --dev ,設定為false的時候將會對JavaScript程式碼進行優化處理。

  • --bundle-output, 生成的jsbundle檔案的名稱,比如./ios/bundle/index.ios.jsbundle

  • --assets-dest 圖片以及其他資源存放的目錄,比如./ios/bundle

打包命令如下:

react-native bundle --entry-file index.ios.js --platform ios --dev false --bundle-output ./ios/bundle/index.ios.jsbundle --assets-dest ./ios/bundle

為了方便使用,也可以把打包命令寫到npm script中:

"scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "bundle-ios":"node node_modules/react-native/local-cli/cli.js bundle --entry-file index.ios.js  --platform ios --dev false --bundle-output ./ios/bundle/index.ios.jsbundle --assets-dest ./ios/bundle"
},

然後執行命令直接打包:

npm run bundle-ios

打包結果:

...
transformed 360/360 (100%)
[8:56:31 PM] <END>   find dependencies (3427ms)
bundle: start
bundle: finish
bundle: Writing bundle output to: ./ios/bundle/index.ios.jsbundle
bundle: Done writing bundle output
bundle: Copying 5 asset files
bundle: Done copying assets

可以看到jsbundle和資原始檔已經打包成功。

新增資源

離線包生成完成之後,可以在ios目錄下看到一個bundle目錄,這個目錄就是bundle生成的離線資源。
需要在Xcode中新增資源到專案中,必須使用Create folder references的方式新增資料夾.

  1. Add Files to "RNIos"

  2. 選擇bundle檔案,在option中選擇Create folder references

  3. 新增到專案中的資料夾必須是藍色

jsCodeLocation

在ios中AppDelegate裡可以看到設定JavaScript程式碼位置的程式碼:
Debug Server上的設定

NSURL *jsCodeLocation;
  jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios&dev=true"];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"RNIos"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];

在開發的過程中可以在這裡配置Debug Server的地址,當釋出上線的時候,就需要使用離線的jsbundle檔案,因此需要設定jsCodeLocation為本地的離線jsbundle。
設定離線的jsCodeLocation:

jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"bundle/index.ios"withExtension:@"jsbundle"];

離線包裡的.jsbundle檔案是經過優化處理的,因此執行效率也會比Debug的時候更高一些。