React Native ios打包

開發React Native的過程成,js代碼和圖片資源運行在一個Debug Server上,每次更新代碼以後只須要使用command+R鍵刷新就能夠看到代碼的更改,這種方式對於調試來講是很是方便的。
但當咱們須要發佈App到App Store的時候就須要打包,使用離線的js代碼和圖片。這就須要把JavaScript和圖片等資源打包成離線資源,在添加到Xcode中,而後一塊兒發佈到App Strore中。
打包離線資源須要使用命令react-native bundle(注:文中使用的項目名稱爲RNIos)node

react-native bundle

React Native的react-native bundle命令是用來進行打包的命令,react-native bundle的詳細命令選項https://github.com/facebook/react-native/blob/master/local-cli/bundle/bundleCommandLineArgs.js
其中咱們常使用的一線命令選項:react

  • --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

打包命令以下:android

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

爲了方便使用,也能夠把打包命令寫到npm script中:git

"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"

  },

而後運行命令直接打包:github

npm run bundle-iosnpm

打包結果:react-native

...
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的方式添加文件夾.spa

  1. Add Files to "RNIos"

    add Files

  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的時候更高一些。

項目代碼地址:https://github.com/jjz/react-native/tree/master/RNIos

相關文章
相關標籤/搜索