React Native ios打包
轉(zhuǎn)自:https://segmentfault.com/a/1190000006668359
?12.2k 次閱讀 ?·? 讀完需要 11 分鐘?
開發(fā)React Native的過程成,js代碼和圖片資源運(yùn)行在一個(gè)Debug Server上牺氨,每次更新代碼之后只需要使用command+R鍵刷新就可以看到代碼的更改,這種方式對(duì)于調(diào)試來說是非常方便的冻璃。
但當(dāng)我們需要發(fā)布App到App Store的時(shí)候就需要打包,使用離線的js代碼和圖片薪夕。這就需要把JavaScript和圖片等資源打包成離線資源递递,在添加到Xcode中,然后一起發(fā)布到App Strore中。
打包離線資源需要使用命令react-native bundle(注:文中使用的項(xiàng)目名稱為RNIos)
react-native bundle
React Native的?react-native bundle命令是用來進(jìn)行打包的命令弹惦,react-native bundle的詳細(xì)命令選項(xiàng)https://github.com/facebook/react-native/blob/master/local-cli/bundle/bundleCommandLineArgs.js矿卑。
其中我們常使用的一線命令選項(xiàng):
--entry-file ,ios或者android入口的js名稱喉恋,比如index.ios.js
--platform ,平臺(tái)名稱(ios或者android)
--dev ,設(shè)置為false的時(shí)候?qū)?huì)對(duì)JavaScript代碼進(jìn)行優(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"},
然后運(yùn)行命令直接打包:
npm run bundle-ios
打包結(jié)果:
...transformed360/360(100%)[8:56:31PM] ? find dependencies (3427ms)bundle:startbundle:finishbundle:Writing bundle outputto:./ios/bundle/index.ios.jsbundlebundle:Done writing bundle outputbundle:Copying5asset filesbundle:Done copying assets
可以看到j(luò)sbundle和資源文件已經(jīng)打包成功。
添加資源
離線包生成完成之后琴昆,可以在ios目錄下看到一個(gè)bundle目錄氓鄙,這個(gè)目錄就是bundle生成的離線資源。
需要在Xcode中添加資源到項(xiàng)目中业舍,必須使用Create folder references的方式添加文件夾.
1 Add Files to "RNIos"
2 選擇bundle文件,在option中選擇Create folder references
3 添加到項(xiàng)目中的文件夾必須是藍(lán)色
jsCodeLocation
在ios中AppDelegate里可以看到設(shè)置JavaScript代碼位置的代碼:
Debug Server上的設(shè)置
NSURL*jsCodeLocation;jsCodeLocation=[NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios&dev=true"];RCTRootView*rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocationmoduleName:@"RNIos"initialProperties:nillaunchOptions:launchOptions];
在開發(fā)的過程中可以在這里配置Debug Server的地址抖拦,當(dāng)發(fā)布上線的時(shí)候,就需要使用離線的jsbundle文件舷暮,因此需要設(shè)置jsCodeLocation為本地的離線jsbundle态罪。
設(shè)置離線的jsCodeLocation:
jsCodeLocation = [[NSBundle mainBundle]?URLForResource:@"bundle/index.ios"withExtension:@"jsbundle"];
離線包里的.jsbundle文件是經(jīng)過優(yōu)化處理的,因此運(yùn)行效率也會(huì)比Debug的時(shí)候更高一些下面。
項(xiàng)目代碼地址:https://github.com/jjz/react-native/tree/master/RNIos