介绍
开发React Native的过程中,js代码和所需要的资源运行在一个Debug Server上,每次代码有更新后,直接command+R就可以在模拟器上看到刷新后的展示,这种方式非常方便。但是我们需要将我们的App发布到AppStore,这个时候就需要打包我们的应用程序,使用离线的js代码和图片资源。这就需要把js和图片等资源打包成离线资源,再添加到Xcode中,然后通过Xcode特殊处理发布到AppStore。
一、生成bundle文件
新建bundle目录
在生成的RN工程中,找到ios目录,在该目录下新建bundle目录
进入项目目录,运行以下打包命令
react-native bundle --entry-file index.js --platform ios --dev false --bundle-output ./ios/bundle/index.ios.jsbundle --assets-dest ./ios/bundle
--entry-file ,ios或者android入口的js名称,比如index.js
--platform ,平台名称(ios或者android)
--dev ,设置为false的时候将会对JavaScript代码进行优化处理。
--bundle-output, 生成的jsbundle文件的名称,比如./ios/bundle/index.ios.jsbundle
--assets-dest 图片以及其他资源存放的目录,比如./ios/bundle
也可以在package.json中添加编译命令
{
"scripts":{
"bundle-ios":"node node_modules/react-native/local-cli/cli.js bundle --entry-file index.js --platform ios --dev false --bundle-output./ios/bundle/index.ios.jsbundle --assets-dest ./ios/bundle"
}
}
以后打包直接运行npm run bundle-ios即可
二、在Xcode中集成
通过上面的命令生成离线包后,可以在ios目录下bundle中看到包含的离线资源:
需要在Xcode中添加资源到项目中,必须选择Create folder references的方式添加文件夹。
添加成功后:
三、设置AppDelegate.m文件
修改AppDelegate.m中的加载包的方式(只需修改一次),之后项目会自动跟据debug还是release状态加载不同的包
NSURL *jsCodeLocation;
#ifdef DEBUG
//开发包
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];#else
//离线包
jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"bundle/index.ios" withExtension:@"jsbundle"];
#endif
修改debug状态
将项目由debug状态改成release状态,Xcode-->Product-->Scheme-->Edit Scheme...
四、添加证书、配置描述文件打包
网友评论