開發React Native的過程成,js代碼和圖片資源運行在一個Debug Server
上,每次更新代碼以後只須要使用command+R
鍵刷新就能夠看到代碼的更改,這種方式對於調試來講是很是方便的。
但當咱們須要發佈App到App Store
的時候就須要打包,使用離線的js代碼和圖片。這就須要把JavaScript和圖片等資源打包成離線資源,在添加到Xcode中,而後一塊兒發佈到App Strore
中。
打包離線資源須要使用命令react-native bundle
(注:文中使用的項目名稱爲RNIos
)node
React Native的react-native bundle
命令是用來進行打包的命令,react-native bundle
的詳細命令選項https://github.com/facebook/react-native/blob/master/local-cli/bundle/bundleCommandLineArgs.js。
其中咱們常使用的一線命令選項:react
./ios/bundle/index.ios.jsbundle
./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
add Files
bundle
文件,在option中選擇Create folder references選擇文件夾
文件夾必須是藍色
在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