開發(fā)React Native的過程成,js代碼和圖片資源運行在一個Debug Server
上唱较,每次更新代碼之后只需要使用command+R
鍵刷新就可以看到代碼的更改深纲,這種方式對于調試來說是非常方便的劫灶。
但當我們需要發(fā)布App到App Store
的時候就需要打包,使用離線的js代碼和圖片。這就需要把JavaScript和圖片等資源打包成離線資源科吭,在添加到Xcode中昏滴,然后一起發(fā)布到App Strore
中。
打包離線資源需要使用命令react-native bundle
(注:文中使用的項目名稱為RNIos
)
react-native bundle
React Native的react-native bundle
命令是用來進行打包的命令对人,react-native bundle
的詳細命令選項https://github.com/facebook/react-native/blob/master/local-cli/bundle/bundleCommandLineArgs.js谣殊。
其中我們常使用的一線命令選項:
- --entry-file ,ios或者android入口的js名稱,比如index.ios.js
- --platform ,平臺名稱(ios或者android)
- --dev ,設置為false的時候將會對JavaScript代碼進行優(yōu)化處理牺弄。
- --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的方式添加文件夾.
-
Add Files to "RNIos"
add Files - 選擇
bundle
文件,在option中選擇Create folder references
選擇文件夾 -
添加到項目中的文件夾必須是藍色
文件夾必須是藍色
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];
在開發(fā)的過程中可以在這里配置Debug Server的地址,當發(fā)布上線的時候回溺,就需要使用離線的jsbundle文件春贸,因此需要設置jsCodeLocation為本地的離線jsbundle混萝。
設置離線的jsCodeLocation:
jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"bundle/index.ios" withExtension:@"jsbundle"];
離線包里的.jsbundle文件是經過優(yōu)化處理的,因此運行效率也會比Debug的時候更高一些萍恕。
項目代碼地址:https://github.com/jjz/react-native/tree/master/RNIos