开发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