React-native iOS打包记录

react-native App打包

Posted by 憧憬 on December 7, 2018

iOS打包

打包命令介绍

  • 通过React Nativereact-native bundle命令来进行打包的。

react-native bundle的详细命令选项

其中常用命令选项:

–entry-file ,ios或者android入口的js名称,比如index.ios.js –platform ,平台名称(ios或者android) –dev ,设置为false的时候将会对JavaScript代码进行优化处理。 –bundle-output, 生成的jsbundle文件的名称,比如release_ios/main.jsbundle –assets-dest 图片以及其他资源存放的目录,比如release_ios/

  • 导出js bundle的命令
1
react-native bundle --entry-file index.ios.js --platform ios --dev false --bundle-output release_ios/main.jsbundle --assets-dest release_ios/
  • 方便使用,可以把打包命令写到npm script
1
2
3
4
5
"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 release_ios/main.jsbundle --assets-dest release_ios/"

  },
  • 运行命令直接打包:
1
npm run bundle-ios

开始打包

第一步:导出js bundle包和图片资源

  • 在React Native项目的根目录下执行打包命令:
1
react-native bundle --entry-file index.ios.js --platform ios --dev false --bundle-output release_ios/main.jsbundle --assets-dest release_ios/

或者 执行:

1
npm run bundle-ios

通过上述命令,将JS部分的代码和图片资源等打包导出到release_ios目录下.

在执行打包命令之前,先确保在项目的根目录有release_ios文件夹,没有的话创建一个。

第二步:将js bundle包和图片资源导入到iOS项目中

  • 这一步需要用到XCode,选择assets文件夹main.jsbundle文件将其拖拽到XCode的项目导航面板中即可。

    必须使用Create folder references的方式添加文件夹.

  • 修改AppDelegate.m文件,添加如下代码:

1
2
3
4
5
6
7
8
9
10
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
 
  NSURL *jsCodeLocation;
 //jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];
 +jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
...
  return YES;
}

让xcode使用刚才导入的jsbundle摆脱对本地nodejs服务器的依赖。

第三步:发布iOS应用