├── .buckconfig ├── .flowconfig ├── .gitattributes ├── .gitignore ├── LICENSE ├── README.md ├── __tests__ └── App-test.js ├── android ├── app │ ├── BUCK │ ├── build.gradle │ ├── build_defs.bzl │ ├── proguard-rules.pro │ └── src │ │ ├── debug │ │ └── AndroidManifest.xml │ │ └── main │ │ ├── AndroidManifest.xml │ │ ├── assets │ │ ├── basics.android.bundle │ │ ├── bundle.zip │ │ ├── business1.android.bundle │ │ ├── business2.android.bundle │ │ ├── business3.android.bundle │ │ └── business4.android.bundle │ │ ├── bundle │ │ ├── basics.android.bundle │ │ ├── business1.android.bundle │ │ ├── business2.android.bundle │ │ ├── business3.android.bundle │ │ └── business4.android.bundle │ │ ├── ic_launcher-web.png │ │ ├── java │ │ └── com │ │ │ └── yxyhail │ │ │ └── metroexample │ │ │ ├── MainActivity.java │ │ │ ├── MainApplication.java │ │ │ ├── react │ │ │ ├── BaseReactActivity.java │ │ │ └── JsLoaderUtil.java │ │ │ ├── ui │ │ │ ├── Business1Activity.java │ │ │ ├── Business2Activity.java │ │ │ ├── Business3Activity.java │ │ │ ├── Business4Activity.java │ │ │ ├── Common1Activity.java │ │ │ └── Common2Activity.java │ │ │ └── utils │ │ │ ├── FileUtil.java │ │ │ └── SpConfig.java │ │ ├── kotlin │ │ └── com │ │ │ └── yxyhail │ │ │ └── metroexample │ │ │ ├── MainActivity.kt │ │ │ ├── MainApplication.kt │ │ │ ├── react │ │ │ ├── BaseReactActivity.kt │ │ │ └── JsLoaderUtil.kt │ │ │ ├── ui │ │ │ ├── Business1Activity.kt │ │ │ ├── Business2Activity.kt │ │ │ ├── Business3Activity.kt │ │ │ ├── Business4Activity.kt │ │ │ ├── Common1Activity.kt │ │ │ └── Common2Activity.kt │ │ │ └── utils │ │ │ ├── FileUtil.kt │ │ │ └── SpConfig.kt │ │ └── res │ │ ├── drawable │ │ ├── ic_launcher_background.xml │ │ └── ic_launcher_foreground.xml │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml ├── build.gradle ├── gradle.properties ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── keystores │ ├── BUCK │ └── debug.keystore.properties └── settings.gradle ├── app.json ├── babel.config.js ├── basics.config.js ├── bundle.sh ├── business.config.js ├── imgs ├── bundle-name-encrypt.png ├── bundle-name.png ├── bundle_help.png ├── ios-img1.png ├── ios-img2.png ├── ios-img3.png ├── ios-img4.png ├── metro.gif ├── metro_config.png ├── moduleid-app.png ├── moduleid-core.png └── moduleid-thirdlib.png ├── index.js ├── ios ├── MetroExample-tvOS │ └── Info.plist ├── MetroExample-tvOSTests │ └── Info.plist ├── MetroExample.xcodeproj │ ├── project.pbxproj │ └── xcshareddata │ │ └── xcschemes │ │ ├── MetroExample-tvOS.xcscheme │ │ └── MetroExample.xcscheme ├── MetroExample │ ├── AppDelegate.h │ ├── AppDelegate.m │ ├── Base.lproj │ │ └── LaunchScreen.xib │ ├── Images.xcassets │ │ ├── AppIcon.appiconset │ │ │ └── Contents.json │ │ └── Contents.json │ ├── Info.plist │ └── main.m └── MetroExampleTests │ ├── Info.plist │ └── MetroExampleTests.m ├── metro.config.js ├── package.json ├── src ├── basics │ └── basics.js ├── business │ ├── Business1.js │ ├── Business2.js │ ├── Business3.js │ └── Business4.js └── index │ ├── index1.js │ ├── index2.js │ ├── index3.js │ └── index4.js └── yarn.lock /.buckconfig: -------------------------------------------------------------------------------- 1 | 2 | [android] 3 | target = Google Inc.:Google APIs:23 4 | 5 | [maven_repositories] 6 | central = https://repo1.maven.org/maven2 7 | -------------------------------------------------------------------------------- /.flowconfig: -------------------------------------------------------------------------------- 1 | [ignore] 2 | ; We fork some components by platform 3 | .*/*[.]android.js 4 | 5 | ; Ignore "BUCK" generated dirs 6 | /\.buckd/ 7 | 8 | ; Ignore unexpected extra "@providesModule" 9 | .*/node_modules/.*/node_modules/fbjs/.* 10 | 11 | ; Ignore duplicate module providers 12 | ; For RN Apps installed via npm, "Libraries" folder is inside 13 | ; "node_modules/react-native" but in the source repo it is in the root 14 | .*/Libraries/react-native/React.js 15 | 16 | ; Ignore polyfills 17 | .*/Libraries/polyfills/.* 18 | 19 | ; Ignore metro 20 | .*/node_modules/metro/.* 21 | 22 | [include] 23 | 24 | [libs] 25 | node_modules/react-native/Libraries/react-native/react-native-interface.js 26 | node_modules/react-native/flow/ 27 | 28 | [options] 29 | emoji=true 30 | 31 | esproposal.optional_chaining=enable 32 | esproposal.nullish_coalescing=enable 33 | 34 | module.system=haste 35 | module.system.haste.use_name_reducers=true 36 | # get basename 37 | module.system.haste.name_reducers='^.*/\([a-zA-Z0-9$_.-]+\.js\(\.flow\)?\)$' -> '\1' 38 | # strip .js or .js.flow suffix 39 | module.system.haste.name_reducers='^\(.*\)\.js\(\.flow\)?$' -> '\1' 40 | # strip .ios suffix 41 | module.system.haste.name_reducers='^\(.*\)\.ios$' -> '\1' 42 | module.system.haste.name_reducers='^\(.*\)\.android$' -> '\1' 43 | module.system.haste.name_reducers='^\(.*\)\.native$' -> '\1' 44 | module.system.haste.paths.blacklist=.*/__tests__/.* 45 | module.system.haste.paths.blacklist=.*/__mocks__/.* 46 | module.system.haste.paths.blacklist=/node_modules/react-native/Libraries/Animated/src/polyfills/.* 47 | module.system.haste.paths.whitelist=/node_modules/react-native/Libraries/.* 48 | 49 | munge_underscores=true 50 | 51 | module.name_mapper='^[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\|pdf\)$' -> 'RelativeImageStub' 52 | 53 | module.file_ext=.js 54 | module.file_ext=.jsx 55 | module.file_ext=.json 56 | module.file_ext=.native.js 57 | 58 | suppress_type=$FlowIssue 59 | suppress_type=$FlowFixMe 60 | suppress_type=$FlowFixMeProps 61 | suppress_type=$FlowFixMeState 62 | 63 | suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\) 64 | suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)?:? #[0-9]+ 65 | suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy 66 | suppress_comment=\\(.\\|\n\\)*\\$FlowExpectedError 67 | 68 | [version] 69 | ^0.92.0 70 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.pbxproj -text 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.ap_ 4 | 5 | # Files for the ART/Dalvik VM 6 | *.dex 7 | 8 | # Java class files 9 | *.class 10 | 11 | # Generated files 12 | bin/ 13 | gen/ 14 | out/ 15 | 16 | # Gradle files 17 | .gradle/ 18 | build/ 19 | 20 | # Local configuration file (sdk path, etc) 21 | local.properties 22 | 23 | # Proguard folder generated by Eclipse 24 | proguard/ 25 | 26 | # Log Files 27 | *.log 28 | 29 | # Android Studio Navigation editor temp files 30 | .navigation/ 31 | 32 | # Android Studio captures folder 33 | captures/ 34 | 35 | # IntelliJ 36 | *.iml 37 | .idea/workspace.xml 38 | .idea/tasks.xml 39 | .idea/gradle.xml 40 | .idea/assetWizardSettings.xml 41 | .idea/dictionaries 42 | .idea/libraries 43 | .idea/caches 44 | 45 | # Keystore files 46 | # Uncomment the following line if you do not want to check your keystore files in. 47 | #*.jks 48 | 49 | # External native build folder generated in Android Studio 2.2 and later 50 | .externalNativeBuild 51 | 52 | # Google Services (e.g. APIs or Firebase) 53 | google-services.json 54 | 55 | # Freeline 56 | freeline.py 57 | freeline/ 58 | freeline_project_description.json 59 | 60 | # fastlane 61 | fastlane/report.xml 62 | fastlane/Preview.html 63 | fastlane/screenshots 64 | fastlane/test_output 65 | fastlane/readme.md 66 | 67 | 68 | # OSX 69 | # 70 | .DS_Store 71 | 72 | # Xcode 73 | # 74 | build/ 75 | *.pbxuser 76 | !default.pbxuser 77 | *.mode1v3 78 | !default.mode1v3 79 | *.mode2v3 80 | !default.mode2v3 81 | *.perspectivev3 82 | !default.perspectivev3 83 | xcuserdata 84 | *.xccheckout 85 | *.moved-aside 86 | DerivedData 87 | *.hmap 88 | *.ipa 89 | *.xcuserstate 90 | project.xcworkspace 91 | 92 | # Android/IntelliJ 93 | # 94 | build/ 95 | .idea 96 | .gradle 97 | local.properties 98 | *.iml 99 | 100 | # node.js 101 | # 102 | node_modules/ 103 | npm-debug.log 104 | yarn-error.log 105 | 106 | # BUCK 107 | buck-out/ 108 | \.buckd/ 109 | *.keystore 110 | 111 | # fastlane 112 | # 113 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 114 | # screenshots whenever they are needed. 115 | # For more information about the recommended setup visit: 116 | # https://docs.fastlane.tools/best-practices/source-control/ 117 | 118 | */fastlane/report.xml 119 | */fastlane/Preview.html 120 | */fastlane/screenshots 121 | 122 | # Bundle artifact 123 | *.jsbundle 124 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # React Native 拆包及实践(iOS&Android) 2 | 3 | ## 一.拆包 4 | 5 | 拆包的方式一般有三种,分别为Facebook的[Metro][metro]、携程的[moles-packer][moles]和diff patch(可以使用Google的[diff-match-patch][diff])。但目前最好的方式可能还是[Metro][metro]。在调研的过程中,接触最早的,也是最全的例子为[react-native-multibundler][multibundler],这个例子甚至开发了可视化工具,进行拆包打包。 6 | 7 | bundle代码拆分类型:基础包与业务包。 8 | 基础包:将一些重复的js代码与第三方依赖库打成一个包。 9 | 业务包:根据应用内的不同业务逻辑,拆分出一个或多个包。 10 | 11 | ### 1.Metro安装 12 | 13 | 实际在运行`npm install`时React Native已经安装Metro了,只不过可能并不是最新版(跟React Native版本有关),想使用最新版Metro,需要单独安装。 14 | 15 | npm install --save-dev metro metro-core 16 | 17 | 或 18 | 19 | yarn add --dev metro metro-core 20 | 21 | ### 2.Metro配置 22 | 23 | 配置Metro有三种方法,分别为`metro.config.js`、`metro.config.json`和`package.json`中添加`metro`字段,常用的方式为 `metro.config.js`。 24 | 25 | [Metro配置][metroConfig]内部结构大致像这样: 26 | 27 | module.exports = { 28 | resolver: { 29 | /* resolver options */ 30 | }, 31 | transformer: { 32 | /* transformer options */ 33 | }, 34 | serializer: { 35 | /* serializer options */ 36 | }, 37 | server: { 38 | /* server options */ 39 | } 40 | 41 | /* general options */ 42 | }; 43 | 44 | 每个optoins内都有很多配置选项,而对于我们这些初学者来说,最重要的是`serializer`选项内的`createModuleIdFactory`与`processModuleFilter`。 45 | 46 | 如图: 47 | 48 | ![][metro-config] 49 | 50 | `createModuleIdFactory` :在[v0.24.1][customid]后,Metro支持了通过此方法配置自定义模块ID,同样支持字符串类型ID,用于生成`require`语句的模块ID,其类型为`() => (path: string) => number`(带有返回参数的返回函数的函数),其中`path`为各个module的完整路径。此方法的另一个用途就是多次打包时,对于同一个模块生成相同的ID,下次更新发版时,不会因ID不同找不到Module。 51 | 52 | `processModuleFilter`:根据给出的条件,对Module进行过滤,将不需要的模块过滤掉。其类型为`(module: Array) => boolean`,其中`module`为输出的模块,里面带着相应的参数,根据返回的波尔值判断是否过滤当前模块。返回`false`为过滤,不打入bundle。 53 | 54 | 接下来上代码: 55 | 56 | function createModuleIdFactory() { 57 | //获取命令行执行的目录,__dirname是nodejs提供的变量 58 | const projectRootPath = __dirname; 59 | return (path) => { 60 | let name = ''; 61 | // 如果需要去除react-native/Libraries路径去除可以放开下面代码 62 | // if (path.indexOf('node_modules' + pathSep + 'react-native' + pathSep + 'Libraries' + pathSep) > 0) { 63 | // //这里是react native 自带的库,因其一般不会改变路径,所以可直接截取最后的文件名称 64 | // name = path.substr(path.lastIndexOf(pathSep) + 1); 65 | // } 66 | if (path.indexOf(projectRootPath) == 0) { 67 | /* 68 | 这里是react native 自带库以外的其他库,因是绝对路径,带有设备信息, 69 | 为了避免重复名称,可以保留node_modules直至结尾 70 | 如/{User}/{username}/{userdir}/node_modules/xxx.js 需要将设备信息截掉 71 | */ 72 | name = path.substr(projectRootPath.length + 1); 73 | } 74 | //js png字符串 文件的后缀名可以去掉 75 | // name = name.replace('.js', ''); 76 | // name = name.replace('.png', ''); 77 | //最后在将斜杠替换为下划线 78 | let regExp = pathSep == '\\' ? new RegExp('\\\\', "gm") : new RegExp(pathSep, "gm"); 79 | name = name.replace(regExp, '_'); 80 | //名称加密 81 | if (isEncrypt) { 82 | name = md5(name); 83 | } 84 | return name; 85 | }; 86 | } 87 | 88 | 需要生成什么样的模块ID,可以根据自己的情况与喜好而定,无论是加密,拼接,甚至可以直接将获取到的`path`返回,唯一注意的是规则要统一,否则会无法找到相应的模块,当然模块ID定的越长,最终的bundle文件就越大,ID长短还是要适中,不过通过MD5加密后,长短已经无所谓了。 89 | 90 | 在打业务包时,可以使用filter对基础包内已有模块进行过滤,减小bundle文件大小。 91 | 92 | function processModuleFilter(module) { 93 | //过滤掉path为__prelude__的一些模块(基础包内已有) 94 | if (module['path'].indexOf('__prelude__') >= 0) { 95 | return false; 96 | } 97 | //过滤掉node_modules内的模块(基础包内已有) 98 | if (module['path'].indexOf(pathSep + 'node_modules' + pathSep) > 0) { 99 | /* 100 | 但输出类型为js/script/virtual的模块不能过滤,一般此类型的文件为核心文件, 101 | 如InitializeCore.js。每次加载bundle文件时都需要用到。 102 | */ 103 | if ('js' + pathSep + 'script' + pathSep + 'virtual' == module['output'][0]['type']) { 104 | return true; 105 | } 106 | return false; 107 | } 108 | //其他就是应用代码 109 | return true; 110 | } 111 | 112 | 在xxx.config.js文件内添加上述两个方法后,将方法引入到`module.exports`内的`serializer`options内。 113 | 114 | module.exports = { 115 | serializer: { 116 | createModuleIdFactory: config.createModuleIdFactory, 117 | processModuleFilter: config.processModuleFilter 118 | /* serializer options */ 119 | } 120 | } 121 | 122 | 123 | ### 3.Metro使用 124 | 125 | 根据基础包业务包的不同,添加 `--config ` 参数对相应入口文件打包。Metro官文虽然标明支持其他路径的配置文件,但至今没有成功过,只能在项目根目录添加配置文件,可能是我添加路径的方式不对,如果你知道如何添加其他路径config.js,请在issue中偷偷告诉我:sweat_smile:。 126 | 127 | 基础包: 128 | 将需要的第三方依赖包与React Native的包、js文件等,可以通过`import`方式引入到一个js文件内,如[basics.js][basics.js],再使用[basics.config.js][basics.config.js]当做参数传入到`--confg`后。 129 | 130 | 131 | 使用终端切换到项目根目录,执行命令: 132 | 133 | react-native bundle --platform android --dev false --entry-file src/basics/basics.js --bundle-output ./android/app/src/main/assets/basics.android.bundle --assets-dest android/app/src/main/res/ --config basics.config.js 134 | 135 | 业务包: 136 | 根据自己应用的业务逻辑,分出不同的业务入口,并使用`AppRegistry`注册业务的主Component,如[index1.js][index1.js],使用[business.config.js][business.config.js]传入到`--config`后。 137 | 138 | 命令如下: 139 | 140 | react-native bundle --platform android --dev false --entry-file src/index/index1.js --bundle-output ./android/app/src/main/assets/business1.android.bundle --assets-dest android/app/src/main/res/ --config business.config.js 141 | 142 | 143 | 将上述两种命令中的路径,替换为自己的路径,分了几个业务包就需要执行几次命令,可以将命令使用`&&`连接,写入到脚本文件内,如Linux的`.sh`或Windows的`.bat`文件,执行脚本文件即可。 144 | 145 | 通过`react-native bundle -h`命令可以查看相应的参数配置选项,其中`--entry-file`为加载的入口文件,如图: 146 | 147 | ![][bundle_help] 148 | 149 | 接下来看下`createModuleIdFactory`的log输出结果: 150 | 151 | 应用内的js: 152 | ![][img-app] 153 | react native的js: 154 | ![][img-core] 155 | 三方依赖库的js: 156 | ![][img-thirdlib] 157 | 158 | 第一行为方法内的`path`路径 159 | 第二行为根据是React Native自带文件还是三方库文件截取名称 160 | 第三行是去除后缀的的名称 161 | 第四行是替换斜杠的名称 162 | 第五行是加密后的字符串 163 | 164 | 如果不加密的话,可以去除项目的目录,否则bundle文件会将项目结构暴露。 165 | 166 | 加密前: 167 | 168 | ![][img-bundle-name] 169 | 170 | 加密后: 171 | 172 | ![][img-bundle-name-encrypt] 173 | 174 | ## 二.Android 原生加载 175 | 176 | :sparkles:目前Demo中使用的是Koltin语言,如果需要Java语言,可以切换[build.gradle][build.gradle]中`isUseKotlin`的值为false后点击Sync按钮进行同步。 177 | 178 | ### 1.源码浅析 179 | 180 | React Native 加载bundle文件有三种方式,分别是从assets目录,本地File目录与Metro本地Server的delta bundle 。而平时用模拟器开发运行,更新文件双击`R`键时,使用的就是delta bundle。接下来就需要寻找加载bundle的接口文件,调用接口完成对不同业务包的加载,而基础包会在调用`createReactContextInBackground`时加载。 181 | 182 | 每个React Native页面都会继承`ReactActivity`,在onCreate方法内,会调用mDelegate.onCreate,在此方法内创建RootView,并设置到ContentView上。 183 | 184 | 看下源码逻辑: 185 | 186 | Delegate.loadApp->ReactRootView.startReactApplication-> 187 | attachToReactInstanceManager->ReactInstanceManager.attachRootView-> 188 | attachRootViewToInstance->ReactRootView.runApplication-> 189 | catalystInstance.getJSModule(AppRegistry.class).runApplication 190 | 191 | 最后会通过CatalystInstance调用runApplication方法进行页面的呈现,如果在没有加载对应的bundle文件时,会报`Application xxx has not been registered.`之类的错误,只需在调用runApplication前将bundle文件加载即可。而接口CatalystInstance继承了一个名为`JSBundleLoaderDelegate`的接口,此接口中的三个方法分别为`loadScriptFromAssets`、`loadScriptFromFile`、`loadScriptFromDeltaBundle`,通过名称可看出是用来load不同位置的bundle的。 192 | 193 | 在ReactRootView的runApplication内,CatalystInstance是调用ReactContext.getCatalystInstance方法获取,而ReactContext内的CatalystInstance是在其创建时从ReactInstanceManager.createReactContext方法内由CatalystInstanceImpl的Builder新建。 194 | 195 | ReactContext可以通过ReactApplication.getReactNativeHost.getReactInstanceManager.getCurrentReactContext获取,因此可以直接自己写一个工具类,在工具类内将需要加载的bundle文件提前加载好即可。 196 | 197 | ### 2.功能实现 198 | 199 | 实现此功能,Demo中用了两种方式,两种方式都需要使用工具类[JsLoaderUtil][JsLoaderUtil]。 200 | 201 | 一种是新建一个类作为基类,它继承`ReactActivity`,并重写了`createReactActivityDelegate`与`getMainComponentName`两个方法,在`createReactActivityDelegate`方法内新建`ReactActivityDelegate`时的`onCreate`方法调用super前,通过工具类将约定的组件加载好。这种方式的好处是,在子类内或进入子类前不用关心加载bundle过程的代码,基类中已经写好了,只需要告诉基类加载哪个业务的bundle文件,如[Business1Activity][Business1Activity]。这种方式的另一个用法就是在进入子类前直接告诉工具类需要加载的bundle文件,而在子类中则无需增加任何代码,仅仅继承`BaseReactActivity`,如[Business2Activity][Business2Activity]。 202 | 203 | public class BaseReactActivity extends ReactActivity { 204 | @Override 205 | protected ReactActivityDelegate createReactActivityDelegate() { 206 | String localBundleName = getBundleName(); 207 | if (!TextUtils.isEmpty(localBundleName)) { 208 | JsLoaderUtil.jsState.bundleName = localBundleName; 209 | } 210 | return new ReactActivityDelegate(this, getMainComponentName()) { 211 | @Override 212 | protected void onCreate(Bundle savedInstanceState) { 213 | JsLoaderUtil.load(getApplication(), 214 | () -> super.onCreate(savedInstanceState)); 215 | } 216 | }; 217 | } 218 | 219 | @Nullable 220 | @Override 221 | protected String getMainComponentName() { 222 | return JsLoaderUtil.jsState.componentName; 223 | } 224 | 225 | protected String getBundleName() { 226 | return ""; 227 | } 228 | 229 | } 230 | 231 | Demo中另一种方式是,让子类直接继承`ReactActivity`,而在进入子类前就用工具类加载好需要的业务bundle文件。这种方式的好处是不用拘泥于继承的父类,但需要注意是在进入页面前,一定要对业务包加载,否则会报错。 232 | 如[Business3Activity][Business3Activity]与[Business4Activity][Business4Activity]。 233 | 234 | ### 3.Double Tap R 235 | 236 | 到此我们的bundle文件已经加载好了,但不可能总是进行打包调试,平时开发时还是需要双击`R`进行热更新加载的。但JS代码都已经进行了业务拆分,并且Application中只对React Native返回了基础包的bundle,业务包分散在各个业务逻辑上。这时就需要一个开关来控制到底是加载文件bundle还是delta bundle,这大致分为三步或四步完成。 237 | 238 | 第一步,在[index.js][index.js]文件内将拆分出来的业务包导入,相当于一次性将业务模块全部注册。 239 | 240 | import './src/index/index1'; 241 | import './src/index/index2'; 242 | import './src/index/index3'; 243 | import './src/index/index4'; 244 | 245 | 第二步,在`JsLoaderUtil`工具类内增加判断,如果是Dev模式,直接返回,不加载bundle并且不调用`createReactContextInBackground`。 246 | 247 | 第三步,在[MainApplication][MainApplication]内`ReactNativeHost`的`getUseDeveloperSupport`方法内返回是否为Dev模式标志,并在`getJSMainModuleName`方法内返回之前的`index.js`名称,告诉React Native此为入口文件。 248 | 249 | 这时就可以进入一个业务页面后,双击`R`更新页面内容了,但在切换开关时重启应用,会无法正常reload,就算进入页面,也会报错崩溃致使被杀掉进程,再进入应用就可以了。与其让它崩溃,不如要么将应用进程杀掉重启,要么增加第四步内容。 250 | 251 | 第四步,在`MainActivity`的`onDestroy`内,调用System.exit(0),切换开关后重启应用就可以正常使用了。 252 | 253 | ### 4.特殊说明 254 | 255 | 每一个js文件都相当于一个Module,而React Native对加载过的Module不会再次加载,也就是说,如果先加载assets内的bundle再加载本地File的bundle文件,呈现的还会是assets内的bundle文件,除非杀掉进程重启后,先加载本地File的bundle文件,才会生效,并没找到很好的解决方法。如果你知道如何解决请在issue中告诉我。 256 | 257 | `assets`目录下的`bundle.zip`压缩包为带有`File`文字的业务包,用来测试从本地File加载功能。而`assets`内其他的业务bundle文件,如[business1.android.bundle][business1.android.bundle],是带有`Assets`文字的bundle包,用来测试从`assets`加载功能。JS代码中,如[Business1.js][Business1.js],是带有`Runtime`文字的业务,用来测试开发过程中双击`R`键热更新功能。 258 | 259 | ### 5.效果演示: 260 | Metro Example 261 | Metro Launcher 262 | 263 | ## 三.iOS 原生加载 264 | ### 1.源码接入 265 | 相对于Android,iOS加载多个bundle文件较简单,只需要对RCTBridge扩展暴露以下接口即可: 266 | 267 | [-(void)executeSourceCode:(NSData *)sourceCode sync:(BOOL)sync;][ios_bridge] 268 | 269 | ### 2.实践(以下是以一个基础包和一个业务包测试) 270 | 1.将打包好的基础包和业务包导入项目中 271 | 272 | 图1: 273 | 274 | ![][ios_img1] 275 | 276 | 2.在App启动时加载基础包 277 | 图2: 278 | 279 | ![][ios_img2] 280 | 281 | 3.在详情页或者加载基础包之后预加载业务包 282 | 283 | 图3: 284 | 285 | ![][ios_img3] 286 | 287 | 4.输出信息:先加载了基础包,后成功加载业务包,且页面&逻辑正常 288 | 289 | 图4: 290 | 291 | ![][ios_img4] 292 | 293 | 294 | ## 四. 功能展望 295 | 296 | 以上就是Demo中的全部内容了,对于下一步的功能展望就是,通过向工具类中传递不同的与服务器定好的模块Key,去下载不同的bundle内容,同样可以根据Key的不同,下载需要更新的图片资源,由工具类拷贝到指定的本地目录,供应用进行更新加载。 297 | 298 | 299 | ## GitHub地址:[https://github.com/yxyhail/MetroExample][example] 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | [example]:https://github.com/yxyhail/MetroExample 310 | [metro]:https://github.com/facebook/metro 311 | [moles]:https://github.com/ctripcorp/moles-packer 312 | [diff]:https://github.com/google/diff-match-patch 313 | [multibundler]:https://github.com/smallnew/react-native-multibundler 314 | [customid]:https://github.com/facebook/metro/issues/6 315 | [License]:http://www.apache.org/licenses/LICENSE-2.0 316 | [metroConfig]:https://facebook.github.io/metro/docs/configuration 317 | 318 | [index.js]:https://github.com/yxyhail/MetroExample/tree/master/index.js 319 | [basics.js]:https://github.com/yxyhail/MetroExample/tree/master/src/basics/basics.js 320 | [index1.js]:https://github.com/yxyhail/MetroExample/tree/master/src/index/index1.js 321 | [business.config.js]:https://github.com/yxyhail/MetroExample/tree/master/business.config.js 322 | [basics.config.js]:https://github.com/yxyhail/MetroExample/tree/master/basics.config.js 323 | [Business1.js]:https://github.com/yxyhail/MetroExample/tree/master/src/business/Business1.js 324 | 325 | [build.gradle]:https://github.com/yxyhail/MetroExample/tree/master/android/app/build.gradle 326 | [Business1Activity]:https://github.com/yxyhail/MetroExample/tree/master/android/app/src/main/kotlin/com/yxyhail/metroexample/ui/Business1Activity.kt 327 | [Business2Activity]:https://github.com/yxyhail/MetroExample/tree/master/android/app/src/main/kotlin/com/yxyhail/metroexample/ui/Business2Activity.kt 328 | [Business3Activity]:https://github.com/yxyhail/MetroExample/tree/master/android/app/src/main/kotlin/com/yxyhail/metroexample/ui/Business3Activity.kt 329 | [Business4Activity]:https://github.com/yxyhail/MetroExample/tree/master/android/app/src/main/kotlin/com/yxyhail/metroexample/ui/Business4Activity.kt 330 | [JsLoaderUtil]:https://github.com/yxyhail/MetroExample/tree/master/android/app/src/main/kotlin/com/yxyhail/metroexample/react/JsLoaderUtil.kt 331 | [MainApplication]:https://github.com/yxyhail/MetroExample/tree/master/android/app/src/main/kotlin/com/yxyhail/metroexample/MainApplication.kt 332 | [business1.android.bundle]:https://github.com/yxyhail/MetroExample/tree/master/android/app/src/main/assets/business1.android.bundle 333 | 334 | [ios_bridge]:https://github.com/chenzhe555/HHZRNRouteManager/blob/master/ios/subpackage_project_test/classes/HHZRNRouteManager/RCTBridge%2BHHZLoadOtherJS.h 335 | 336 | [ios_img1]:https://raw.githubusercontent.com/yxyhail/MetroExample/master/imgs/ios-img1.png 337 | [ios_img2]:https://raw.githubusercontent.com/yxyhail/MetroExample/master/imgs/ios-img2.png 338 | [ios_img3]:https://raw.githubusercontent.com/yxyhail/MetroExample/master/imgs/ios-img3.png 339 | [ios_img4]:https://raw.githubusercontent.com/yxyhail/MetroExample/master/imgs/ios-img4.png 340 | 341 | [img-app]:https://raw.githubusercontent.com/yxyhail/MetroExample/master/imgs/moduleid-app.png 342 | [img-core]:https://raw.githubusercontent.com/yxyhail/MetroExample/master/imgs/moduleid-core.png 343 | [img-thirdlib]:https://raw.githubusercontent.com/yxyhail/MetroExample/master/imgs/moduleid-thirdlib.png 344 | [img-bundle-name]:https://raw.githubusercontent.com/yxyhail/MetroExample/master/imgs/bundle-name.png 345 | [img-bundle-name-encrypt]:https://raw.githubusercontent.com/yxyhail/MetroExample/master/imgs/bundle-name-encrypt.png 346 | [bundle_help]:https://raw.githubusercontent.com/yxyhail/MetroExample/master/imgs/bundle_help.png 347 | [metro-config]:https://raw.githubusercontent.com/yxyhail/MetroExample/master/imgs/metro_config.png 348 | -------------------------------------------------------------------------------- /__tests__/App-test.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @format 3 | */ 4 | 5 | import 'react-native'; 6 | import React from 'react'; 7 | import App from '../App'; 8 | 9 | // Note: test renderer must be required after react-native. 10 | import renderer from 'react-test-renderer'; 11 | 12 | it('renders correctly', () => { 13 | renderer.create(); 14 | }); 15 | -------------------------------------------------------------------------------- /android/app/BUCK: -------------------------------------------------------------------------------- 1 | # To learn about Buck see [Docs](https://buckbuild.com/). 2 | # To run your application with Buck: 3 | # - install Buck 4 | # - `npm start` - to start the packager 5 | # - `cd android` 6 | # - `keytool -genkey -v -keystore keystores/debug.keystore -storepass android -alias androiddebugkey -keypass android -dname "CN=Android Debug,O=Android,C=US"` 7 | # - `./gradlew :app:copyDownloadableDepsToLibs` - make all Gradle compile dependencies available to Buck 8 | # - `buck install -r android/app` - compile, install and run application 9 | # 10 | 11 | load(":build_defs.bzl", "create_aar_targets", "create_jar_targets") 12 | 13 | lib_deps = [] 14 | 15 | create_aar_targets(glob(["libs/*.aar"])) 16 | 17 | create_jar_targets(glob(["libs/*.jar"])) 18 | 19 | android_library( 20 | name = "all-libs", 21 | exported_deps = lib_deps, 22 | ) 23 | 24 | android_library( 25 | name = "app-code", 26 | srcs = glob([ 27 | "src/main/java/**/*.java", 28 | ]), 29 | deps = [ 30 | ":all-libs", 31 | ":build_config", 32 | ":res", 33 | ], 34 | ) 35 | 36 | android_build_config( 37 | name = "build_config", 38 | package = "com.yxyhail.com.yxyhail.metroexample", 39 | ) 40 | 41 | android_resource( 42 | name = "res", 43 | package = "com.yxyhail.com.yxyhail.metroexample", 44 | res = "src/main/res", 45 | ) 46 | 47 | android_binary( 48 | name = "app", 49 | keystore = "//android/keystores:debug", 50 | manifest = "src/main/AndroidManifest.xml", 51 | package_type = "debug", 52 | deps = [ 53 | ":app-code", 54 | ], 55 | ) 56 | -------------------------------------------------------------------------------- /android/app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: "com.android.application" 2 | 3 | apply plugin: 'kotlin-android' 4 | apply plugin: 'kotlin-android-extensions' 5 | 6 | 7 | import com.android.build.OutputFile 8 | 9 | /** 10 | * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets 11 | * and bundleReleaseJsAndAssets). 12 | * These basically call `react-native bundle` with the correct arguments during the Android build 13 | * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the 14 | * bundle directly from the development server. Below you can see all the possible configurations 15 | * and their defaults. If you decide to add a configuration block, make sure to add it before the 16 | * `apply from: "../../node_modules/react-native/react.gradle"` line. 17 | * 18 | * project.ext.react = [ 19 | * // the name of the generated asset file containing your JS bundle 20 | * bundleAssetName: "index.android.bundle", 21 | * 22 | * // the entry file for bundle generation 23 | * entryFile: "index.android.js", 24 | * 25 | * // whether to bundle JS and assets in debug mode 26 | * bundleInDebug: false, 27 | * 28 | * // whether to bundle JS and assets in release mode 29 | * bundleInRelease: true, 30 | * 31 | * // whether to bundle JS and assets in another build variant (if configured). 32 | * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants 33 | * // The configuration property can be in the following formats 34 | * // 'bundleIn${productFlavor}${buildType}' 35 | * // 'bundleIn${buildType}' 36 | * // bundleInFreeDebug: true, 37 | * // bundleInPaidRelease: true, 38 | * // bundleInBeta: true, 39 | * 40 | * // whether to disable dev mode in custom build variants (by default only disabled in release) 41 | * // for example: to disable dev mode in the staging build type (if configured) 42 | * devDisabledInStaging: true, 43 | * // The configuration property can be in the following formats 44 | * // 'devDisabledIn${productFlavor}${buildType}' 45 | * // 'devDisabledIn${buildType}' 46 | * 47 | * // the root of your project, i.e. where "package.json" lives 48 | * root: "../../", 49 | * 50 | * // where to put the JS bundle asset in debug mode 51 | * jsBundleDirDebug: "$buildDir/intermediates/assets/debug", 52 | * 53 | * // where to put the JS bundle asset in release mode 54 | * jsBundleDirRelease: "$buildDir/intermediates/assets/release", 55 | * 56 | * // where to put drawable resources / React Native assets, e.g. the ones you use via 57 | * // require('./image.png')), in debug mode 58 | * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug", 59 | * 60 | * // where to put drawable resources / React Native assets, e.g. the ones you use via 61 | * // require('./image.png')), in release mode 62 | * resourcesDirRelease: "$buildDir/intermediates/res/merged/release", 63 | * 64 | * // by default the gradle tasks are skipped if none of the JS files or assets change; this means 65 | * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to 66 | * // date; if you have any other folders that you want to ignore for performance reasons (gradle 67 | * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/ 68 | * // for example, you might want to remove it from here. 69 | * inputExcludes: ["android/**", "ios/**"], 70 | * 71 | * // override which node gets called and with what additional arguments 72 | * nodeExecutableAndArgs: ["node"], 73 | * 74 | * // supply additional arguments to the packager 75 | * extraPackagerArgs: [] 76 | * ] 77 | */ 78 | 79 | project.ext.react = [ 80 | entryFile: "index.js" 81 | ] 82 | 83 | apply from: "../../node_modules/react-native/react.gradle" 84 | 85 | /** 86 | * Set this to true to create two separate APKs instead of one: 87 | * - An APK that only works on ARM devices 88 | * - An APK that only works on x86 devices 89 | * The advantage is the size of the APK is reduced by about 4MB. 90 | * Upload all the APKs to the Play Store and people will download 91 | * the correct one based on the CPU architecture of their device. 92 | */ 93 | def enableSeparateBuildPerCPUArchitecture = false 94 | 95 | /** 96 | * Run Proguard to shrink the Java bytecode in release builds. 97 | */ 98 | def enableProguardInReleaseBuilds = false 99 | 100 | //切换语言 false 为Java 101 | def isUseKotlin = true 102 | 103 | android { 104 | compileSdkVersion rootProject.ext.compileSdkVersion 105 | 106 | compileOptions { 107 | sourceCompatibility JavaVersion.VERSION_1_8 108 | targetCompatibility JavaVersion.VERSION_1_8 109 | } 110 | 111 | defaultConfig { 112 | applicationId "com.yxyhail.metroexample" 113 | minSdkVersion rootProject.ext.minSdkVersion 114 | targetSdkVersion rootProject.ext.targetSdkVersion 115 | versionCode 1 116 | versionName "1.0" 117 | } 118 | splits { 119 | abi { 120 | reset() 121 | enable enableSeparateBuildPerCPUArchitecture 122 | universalApk false // If true, also generate a universal APK 123 | include "armeabi-v7a", "x86", "arm64-v8a", "x86_64" 124 | } 125 | } 126 | buildTypes { 127 | release { 128 | minifyEnabled enableProguardInReleaseBuilds 129 | proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" 130 | } 131 | } 132 | // applicationVariants are e.g. debug, release 133 | applicationVariants.all { variant -> 134 | variant.outputs.each { output -> 135 | // For each separate APK per architecture, set a unique version code as described here: 136 | // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits 137 | def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4] 138 | def abi = output.getFilter(OutputFile.ABI) 139 | if (abi != null) { // null for the universal-debug, universal-release variants 140 | output.versionCodeOverride = 141 | versionCodes.get(abi) * 1048576 + defaultConfig.versionCode 142 | } 143 | } 144 | } 145 | 146 | 147 | sourceSets { 148 | if(isUseKotlin){ 149 | main.java.srcDirs = files('./src/main/kotlin') 150 | } 151 | } 152 | } 153 | 154 | dependencies { 155 | implementation fileTree(dir: "libs", include: ["*.jar"]) 156 | implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}" 157 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 158 | implementation "com.facebook.react:react-native:+" // From node_modules 159 | } 160 | 161 | // Run this once to be able to run the application with BUCK 162 | // puts all compile dependencies into folder libs for BUCK to use 163 | task copyDownloadableDepsToLibs(type: Copy) { 164 | from configurations.compile 165 | into 'libs' 166 | } 167 | -------------------------------------------------------------------------------- /android/app/build_defs.bzl: -------------------------------------------------------------------------------- 1 | """Helper definitions to glob .aar and .jar targets""" 2 | 3 | def create_aar_targets(aarfiles): 4 | for aarfile in aarfiles: 5 | name = "aars__" + aarfile[aarfile.rindex("/") + 1:aarfile.rindex(".aar")] 6 | lib_deps.append(":" + name) 7 | android_prebuilt_aar( 8 | name = name, 9 | aar = aarfile, 10 | ) 11 | 12 | def create_jar_targets(jarfiles): 13 | for jarfile in jarfiles: 14 | name = "jars__" + jarfile[jarfile.rindex("/") + 1:jarfile.rindex(".jar")] 15 | lib_deps.append(":" + name) 16 | prebuilt_jar( 17 | name = name, 18 | binary_jar = jarfile, 19 | ) 20 | -------------------------------------------------------------------------------- /android/app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /android/app/src/debug/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /android/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 19 | 20 | 21 | 22 | 29 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /android/app/src/main/assets/bundle.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yxyhail/MetroExample/0180d2f08ae7849b6838aba379db1a4f69bc5109/android/app/src/main/assets/bundle.zip -------------------------------------------------------------------------------- /android/app/src/main/assets/business1.android.bundle: -------------------------------------------------------------------------------- 1 | __d(function(g,r,i,a,m,e,d){var n=r(d[0]),t=r(d[1]),p=n(r(d[2]));t.AppRegistry.registerComponent('App1',function(){return p.default})},"c6c2c8469af7295f23892fe6674462dc",["3e65d9ce974965f47088216bd50f5085","e8d3739a2784712b22549b81cc277c73","96ebb010ddf6eb23b62a6f4937ace689"]); 2 | __d(function(g,r,i,a,m,e,d){var t=r(d[0]),n=r(d[1]);Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var l=n(r(d[2])),s=n(r(d[3])),u=n(r(d[4])),o=n(r(d[5])),c=n(r(d[6])),f=t(r(d[7])),y=r(d[8]),v=(function(t){function n(){return(0,l.default)(this,n),(0,u.default)(this,(0,o.default)(n).apply(this,arguments))}return(0,c.default)(n,t),(0,s.default)(n,[{key:"render",value:function(){return f.default.createElement(y.View,{style:x.container},f.default.createElement(y.Text,{style:x.welcome},"\u6b22\u8fce\u6765\u5230","Business1","\uff01Load From Assets"),f.default.createElement(y.Text,{style:x.instructions},"To get started, edit ","Business1",".js"),f.default.createElement(y.Text,{style:x.instructions},"Business1"))}}]),n})(f.Component);e.default=v;var x=y.StyleSheet.create({container:{flex:1,justifyContent:'center',alignItems:'center',backgroundColor:'#F5FCFF'},welcome:{fontSize:20,textAlign:'center',margin:10},instructions:{textAlign:'center',color:'#333333',marginBottom:5}})},"96ebb010ddf6eb23b62a6f4937ace689",["3495981ab64e6294f806af1440f3d1cc","3e65d9ce974965f47088216bd50f5085","7aadbf3e1417e832c0de5d69fdf8d2f4","8df63d2876f048ce7122a42935c301d4","74f080d293e532e00012d3630c735047","8c3f37c4e6718385e1712cec51101117","2e44aa2fac71d2c2220634fa12f86093","2c4d30703ab8e5d9543b5c3fe87b72c2","e8d3739a2784712b22549b81cc277c73"]); 3 | __r("4e053c1391f5aa8e5d34f15159692cee"); 4 | __r("c6c2c8469af7295f23892fe6674462dc"); -------------------------------------------------------------------------------- /android/app/src/main/assets/business2.android.bundle: -------------------------------------------------------------------------------- 1 | __d(function(g,r,i,a,m,e,d){var n=r(d[0]),t=r(d[1]),p=n(r(d[2]));t.AppRegistry.registerComponent('App2',function(){return p.default})},"1ce0dd1e34e287c8156bc495abbae19f",["3e65d9ce974965f47088216bd50f5085","e8d3739a2784712b22549b81cc277c73","0a6832275020d0be2e3f0f05387462d8"]); 2 | __d(function(g,r,i,a,m,e,d){var t=r(d[0]),n=r(d[1]);Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var l=n(r(d[2])),s=n(r(d[3])),u=n(r(d[4])),o=n(r(d[5])),c=n(r(d[6])),f=t(r(d[7])),y=r(d[8]),v=(function(t){function n(){return(0,l.default)(this,n),(0,u.default)(this,(0,o.default)(n).apply(this,arguments))}return(0,c.default)(n,t),(0,s.default)(n,[{key:"render",value:function(){return f.default.createElement(y.View,{style:x.container},f.default.createElement(y.Text,{style:x.welcome},"\u6b22\u8fce\u6765\u5230","Business2","\uff01Load From Assets"),f.default.createElement(y.Text,{style:x.instructions},"To get started, edit ","Business2",".js"),f.default.createElement(y.Text,{style:x.instructions},"Business2"))}}]),n})(f.Component);e.default=v;var x=y.StyleSheet.create({container:{flex:1,justifyContent:'center',alignItems:'center',backgroundColor:'#F5FCFF'},welcome:{fontSize:20,textAlign:'center',margin:10},instructions:{textAlign:'center',color:'#333333',marginBottom:5}})},"0a6832275020d0be2e3f0f05387462d8",["3495981ab64e6294f806af1440f3d1cc","3e65d9ce974965f47088216bd50f5085","7aadbf3e1417e832c0de5d69fdf8d2f4","8df63d2876f048ce7122a42935c301d4","74f080d293e532e00012d3630c735047","8c3f37c4e6718385e1712cec51101117","2e44aa2fac71d2c2220634fa12f86093","2c4d30703ab8e5d9543b5c3fe87b72c2","e8d3739a2784712b22549b81cc277c73"]); 3 | __r("4e053c1391f5aa8e5d34f15159692cee"); 4 | __r("1ce0dd1e34e287c8156bc495abbae19f"); -------------------------------------------------------------------------------- /android/app/src/main/assets/business3.android.bundle: -------------------------------------------------------------------------------- 1 | __d(function(g,r,i,a,m,e,d){var n=r(d[0]),t=r(d[1]),p=n(r(d[2]));t.AppRegistry.registerComponent('App3',function(){return p.default})},"9516ab4f0a8d8f2dbb19dcb95984ba3a",["3e65d9ce974965f47088216bd50f5085","e8d3739a2784712b22549b81cc277c73","d2b3667a93b0490f727ad226ed0a2ce0"]); 2 | __d(function(g,r,i,a,m,e,d){var t=r(d[0]),n=r(d[1]);Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var l=n(r(d[2])),s=n(r(d[3])),u=n(r(d[4])),o=n(r(d[5])),c=n(r(d[6])),f=t(r(d[7])),y=r(d[8]),v=(function(t){function n(){return(0,l.default)(this,n),(0,u.default)(this,(0,o.default)(n).apply(this,arguments))}return(0,c.default)(n,t),(0,s.default)(n,[{key:"render",value:function(){return f.default.createElement(y.View,{style:x.container},f.default.createElement(y.Text,{style:x.welcome},"\u6b22\u8fce\u6765\u5230","Business3","\uff01Load From Assets"),f.default.createElement(y.Text,{style:x.instructions},"To get started, edit ","Business3",".js"),f.default.createElement(y.Text,{style:x.instructions},"Business3"))}}]),n})(f.Component);e.default=v;var x=y.StyleSheet.create({container:{flex:1,justifyContent:'center',alignItems:'center',backgroundColor:'#F5FCFF'},welcome:{fontSize:20,textAlign:'center',margin:10},instructions:{textAlign:'center',color:'#333333',marginBottom:5}})},"d2b3667a93b0490f727ad226ed0a2ce0",["3495981ab64e6294f806af1440f3d1cc","3e65d9ce974965f47088216bd50f5085","7aadbf3e1417e832c0de5d69fdf8d2f4","8df63d2876f048ce7122a42935c301d4","74f080d293e532e00012d3630c735047","8c3f37c4e6718385e1712cec51101117","2e44aa2fac71d2c2220634fa12f86093","2c4d30703ab8e5d9543b5c3fe87b72c2","e8d3739a2784712b22549b81cc277c73"]); 3 | __r("4e053c1391f5aa8e5d34f15159692cee"); 4 | __r("9516ab4f0a8d8f2dbb19dcb95984ba3a"); -------------------------------------------------------------------------------- /android/app/src/main/assets/business4.android.bundle: -------------------------------------------------------------------------------- 1 | __d(function(g,r,i,a,m,e,d){var n=r(d[0]),t=r(d[1]),p=n(r(d[2]));t.AppRegistry.registerComponent('App4',function(){return p.default})},"cbd4897f3b1910bb96a6e52ff2f689b9",["3e65d9ce974965f47088216bd50f5085","e8d3739a2784712b22549b81cc277c73","87c0385140de44953b25eace3eac8498"]); 2 | __d(function(g,r,i,a,m,e,d){var t=r(d[0]),n=r(d[1]);Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var l=n(r(d[2])),s=n(r(d[3])),u=n(r(d[4])),o=n(r(d[5])),c=n(r(d[6])),f=t(r(d[7])),y=r(d[8]),v=(function(t){function n(){return(0,l.default)(this,n),(0,u.default)(this,(0,o.default)(n).apply(this,arguments))}return(0,c.default)(n,t),(0,s.default)(n,[{key:"render",value:function(){return f.default.createElement(y.View,{style:x.container},f.default.createElement(y.Text,{style:x.welcome},"\u6b22\u8fce\u6765\u5230","Business4","\uff01Load From Assets"),f.default.createElement(y.Text,{style:x.instructions},"To get started, edit ","Business4",".js"),f.default.createElement(y.Text,{style:x.instructions},"Business4"))}}]),n})(f.Component);e.default=v;var x=y.StyleSheet.create({container:{flex:1,justifyContent:'center',alignItems:'center',backgroundColor:'#F5FCFF'},welcome:{fontSize:20,textAlign:'center',margin:10},instructions:{textAlign:'center',color:'#333333',marginBottom:5}})},"87c0385140de44953b25eace3eac8498",["3495981ab64e6294f806af1440f3d1cc","3e65d9ce974965f47088216bd50f5085","7aadbf3e1417e832c0de5d69fdf8d2f4","8df63d2876f048ce7122a42935c301d4","74f080d293e532e00012d3630c735047","8c3f37c4e6718385e1712cec51101117","2e44aa2fac71d2c2220634fa12f86093","2c4d30703ab8e5d9543b5c3fe87b72c2","e8d3739a2784712b22549b81cc277c73"]); 3 | __r("4e053c1391f5aa8e5d34f15159692cee"); 4 | __r("cbd4897f3b1910bb96a6e52ff2f689b9"); -------------------------------------------------------------------------------- /android/app/src/main/bundle/business1.android.bundle: -------------------------------------------------------------------------------- 1 | __d(function(g,r,i,a,m,e,d){var n=r(d[0]),t=r(d[1]),p=n(r(d[2]));t.AppRegistry.registerComponent('App1',function(){return p.default})},"c6c2c8469af7295f23892fe6674462dc",["3e65d9ce974965f47088216bd50f5085","e8d3739a2784712b22549b81cc277c73","96ebb010ddf6eb23b62a6f4937ace689"]); 2 | __d(function(g,r,i,a,m,e,d){var t=r(d[0]),n=r(d[1]);Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var l=n(r(d[2])),u=n(r(d[3])),o=n(r(d[4])),s=n(r(d[5])),c=n(r(d[6])),f=t(r(d[7])),y=r(d[8]),v=(function(t){function n(){return(0,l.default)(this,n),(0,o.default)(this,(0,s.default)(n).apply(this,arguments))}return(0,c.default)(n,t),(0,u.default)(n,[{key:"render",value:function(){return f.default.createElement(y.View,{style:x.container},f.default.createElement(y.Text,{style:x.welcome},"\u6b22\u8fce\u6765\u5230","Business1","\uff01Load From File"),f.default.createElement(y.Text,{style:x.instructions},"To get started, edit ","Business1",".js"),f.default.createElement(y.Text,{style:x.instructions},"Business1"))}}]),n})(f.Component);e.default=v;var x=y.StyleSheet.create({container:{flex:1,justifyContent:'center',alignItems:'center',backgroundColor:'#F5FCFF'},welcome:{fontSize:20,textAlign:'center',margin:10},instructions:{textAlign:'center',color:'#333333',marginBottom:5}})},"96ebb010ddf6eb23b62a6f4937ace689",["3495981ab64e6294f806af1440f3d1cc","3e65d9ce974965f47088216bd50f5085","7aadbf3e1417e832c0de5d69fdf8d2f4","8df63d2876f048ce7122a42935c301d4","74f080d293e532e00012d3630c735047","8c3f37c4e6718385e1712cec51101117","2e44aa2fac71d2c2220634fa12f86093","2c4d30703ab8e5d9543b5c3fe87b72c2","e8d3739a2784712b22549b81cc277c73"]); 3 | __r("4e053c1391f5aa8e5d34f15159692cee"); 4 | __r("c6c2c8469af7295f23892fe6674462dc"); -------------------------------------------------------------------------------- /android/app/src/main/bundle/business2.android.bundle: -------------------------------------------------------------------------------- 1 | __d(function(g,r,i,a,m,e,d){var n=r(d[0]),t=r(d[1]),p=n(r(d[2]));t.AppRegistry.registerComponent('App2',function(){return p.default})},"1ce0dd1e34e287c8156bc495abbae19f",["3e65d9ce974965f47088216bd50f5085","e8d3739a2784712b22549b81cc277c73","0a6832275020d0be2e3f0f05387462d8"]); 2 | __d(function(g,r,i,a,m,e,d){var t=r(d[0]),n=r(d[1]);Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var l=n(r(d[2])),u=n(r(d[3])),o=n(r(d[4])),s=n(r(d[5])),c=n(r(d[6])),f=t(r(d[7])),y=r(d[8]),v=(function(t){function n(){return(0,l.default)(this,n),(0,o.default)(this,(0,s.default)(n).apply(this,arguments))}return(0,c.default)(n,t),(0,u.default)(n,[{key:"render",value:function(){return f.default.createElement(y.View,{style:x.container},f.default.createElement(y.Text,{style:x.welcome},"\u6b22\u8fce\u6765\u5230","Business2","\uff01Load From File"),f.default.createElement(y.Text,{style:x.instructions},"To get started, edit ","Business2",".js"),f.default.createElement(y.Text,{style:x.instructions},"Business2"))}}]),n})(f.Component);e.default=v;var x=y.StyleSheet.create({container:{flex:1,justifyContent:'center',alignItems:'center',backgroundColor:'#F5FCFF'},welcome:{fontSize:20,textAlign:'center',margin:10},instructions:{textAlign:'center',color:'#333333',marginBottom:5}})},"0a6832275020d0be2e3f0f05387462d8",["3495981ab64e6294f806af1440f3d1cc","3e65d9ce974965f47088216bd50f5085","7aadbf3e1417e832c0de5d69fdf8d2f4","8df63d2876f048ce7122a42935c301d4","74f080d293e532e00012d3630c735047","8c3f37c4e6718385e1712cec51101117","2e44aa2fac71d2c2220634fa12f86093","2c4d30703ab8e5d9543b5c3fe87b72c2","e8d3739a2784712b22549b81cc277c73"]); 3 | __r("4e053c1391f5aa8e5d34f15159692cee"); 4 | __r("1ce0dd1e34e287c8156bc495abbae19f"); -------------------------------------------------------------------------------- /android/app/src/main/bundle/business3.android.bundle: -------------------------------------------------------------------------------- 1 | __d(function(g,r,i,a,m,e,d){var n=r(d[0]),t=r(d[1]),p=n(r(d[2]));t.AppRegistry.registerComponent('App3',function(){return p.default})},"9516ab4f0a8d8f2dbb19dcb95984ba3a",["3e65d9ce974965f47088216bd50f5085","e8d3739a2784712b22549b81cc277c73","d2b3667a93b0490f727ad226ed0a2ce0"]); 2 | __d(function(g,r,i,a,m,e,d){var t=r(d[0]),n=r(d[1]);Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var l=n(r(d[2])),u=n(r(d[3])),o=n(r(d[4])),s=n(r(d[5])),c=n(r(d[6])),f=t(r(d[7])),y=r(d[8]),v=(function(t){function n(){return(0,l.default)(this,n),(0,o.default)(this,(0,s.default)(n).apply(this,arguments))}return(0,c.default)(n,t),(0,u.default)(n,[{key:"render",value:function(){return f.default.createElement(y.View,{style:x.container},f.default.createElement(y.Text,{style:x.welcome},"\u6b22\u8fce\u6765\u5230","Business3","\uff01Load From File"),f.default.createElement(y.Text,{style:x.instructions},"To get started, edit ","Business3",".js"),f.default.createElement(y.Text,{style:x.instructions},"Business3"))}}]),n})(f.Component);e.default=v;var x=y.StyleSheet.create({container:{flex:1,justifyContent:'center',alignItems:'center',backgroundColor:'#F5FCFF'},welcome:{fontSize:20,textAlign:'center',margin:10},instructions:{textAlign:'center',color:'#333333',marginBottom:5}})},"d2b3667a93b0490f727ad226ed0a2ce0",["3495981ab64e6294f806af1440f3d1cc","3e65d9ce974965f47088216bd50f5085","7aadbf3e1417e832c0de5d69fdf8d2f4","8df63d2876f048ce7122a42935c301d4","74f080d293e532e00012d3630c735047","8c3f37c4e6718385e1712cec51101117","2e44aa2fac71d2c2220634fa12f86093","2c4d30703ab8e5d9543b5c3fe87b72c2","e8d3739a2784712b22549b81cc277c73"]); 3 | __r("4e053c1391f5aa8e5d34f15159692cee"); 4 | __r("9516ab4f0a8d8f2dbb19dcb95984ba3a"); -------------------------------------------------------------------------------- /android/app/src/main/bundle/business4.android.bundle: -------------------------------------------------------------------------------- 1 | __d(function(g,r,i,a,m,e,d){var n=r(d[0]),t=r(d[1]),p=n(r(d[2]));t.AppRegistry.registerComponent('App4',function(){return p.default})},"cbd4897f3b1910bb96a6e52ff2f689b9",["3e65d9ce974965f47088216bd50f5085","e8d3739a2784712b22549b81cc277c73","87c0385140de44953b25eace3eac8498"]); 2 | __d(function(g,r,i,a,m,e,d){var t=r(d[0]),n=r(d[1]);Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var l=n(r(d[2])),u=n(r(d[3])),o=n(r(d[4])),s=n(r(d[5])),c=n(r(d[6])),f=t(r(d[7])),y=r(d[8]),v=(function(t){function n(){return(0,l.default)(this,n),(0,o.default)(this,(0,s.default)(n).apply(this,arguments))}return(0,c.default)(n,t),(0,u.default)(n,[{key:"render",value:function(){return f.default.createElement(y.View,{style:x.container},f.default.createElement(y.Text,{style:x.welcome},"\u6b22\u8fce\u6765\u5230","Business4","\uff01Load From File"),f.default.createElement(y.Text,{style:x.instructions},"To get started, edit ","Business4",".js"),f.default.createElement(y.Text,{style:x.instructions},"Business4"))}}]),n})(f.Component);e.default=v;var x=y.StyleSheet.create({container:{flex:1,justifyContent:'center',alignItems:'center',backgroundColor:'#F5FCFF'},welcome:{fontSize:20,textAlign:'center',margin:10},instructions:{textAlign:'center',color:'#333333',marginBottom:5}})},"87c0385140de44953b25eace3eac8498",["3495981ab64e6294f806af1440f3d1cc","3e65d9ce974965f47088216bd50f5085","7aadbf3e1417e832c0de5d69fdf8d2f4","8df63d2876f048ce7122a42935c301d4","74f080d293e532e00012d3630c735047","8c3f37c4e6718385e1712cec51101117","2e44aa2fac71d2c2220634fa12f86093","2c4d30703ab8e5d9543b5c3fe87b72c2","e8d3739a2784712b22549b81cc277c73"]); 3 | __r("4e053c1391f5aa8e5d34f15159692cee"); 4 | __r("cbd4897f3b1910bb96a6e52ff2f689b9"); -------------------------------------------------------------------------------- /android/app/src/main/ic_launcher-web.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yxyhail/MetroExample/0180d2f08ae7849b6838aba379db1a4f69bc5109/android/app/src/main/ic_launcher-web.png -------------------------------------------------------------------------------- /android/app/src/main/java/com/yxyhail/metroexample/MainActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 yxyhail 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yxyhail.metroexample; 18 | 19 | import android.content.Intent; 20 | import android.os.Bundle; 21 | import android.os.Handler; 22 | import android.support.annotation.Nullable; 23 | import android.support.v7.app.AppCompatActivity; 24 | import android.view.View; 25 | import android.widget.Switch; 26 | import android.widget.TextView; 27 | 28 | import com.yxyhail.metroexample.react.JsLoaderUtil; 29 | import com.yxyhail.metroexample.ui.Business1Activity; 30 | import com.yxyhail.metroexample.ui.Business2Activity; 31 | import com.yxyhail.metroexample.ui.Business3Activity; 32 | import com.yxyhail.metroexample.ui.Business4Activity; 33 | import com.yxyhail.metroexample.ui.Common1Activity; 34 | import com.yxyhail.metroexample.ui.Common2Activity; 35 | import com.yxyhail.metroexample.utils.FileUtil; 36 | import com.yxyhail.metroexample.utils.SpConfig; 37 | 38 | import java.io.File; 39 | import java.util.Arrays; 40 | 41 | 42 | public class MainActivity extends AppCompatActivity implements View.OnClickListener { 43 | private int index = 0; 44 | private TextView common1; 45 | private TextView common2; 46 | 47 | @Override 48 | protected void onCreate(@Nullable Bundle savedInstanceState) { 49 | super.onCreate(savedInstanceState); 50 | setContentView(R.layout.activity_main); 51 | findViewById(R.id.business1).setOnClickListener(this); 52 | findViewById(R.id.business2).setOnClickListener(this); 53 | findViewById(R.id.business3).setOnClickListener(this); 54 | findViewById(R.id.business4).setOnClickListener(this); 55 | JsLoaderUtil.jsState.isFilePrior = true; 56 | 57 | //模拟下载Bundle到本地File 58 | JsLoaderUtil.setDefaultFileDir(getApplication()); 59 | File file = FileUtil.copyAssetsFile(this, "bundle.zip"); 60 | FileUtil.unZip(file, getFilesDir().getAbsolutePath()); 61 | 62 | SpConfig.setIndex(0); 63 | 64 | common1 = findViewById(R.id.intent_to_common1); 65 | common1.setOnClickListener(this); 66 | 67 | common2 = findViewById(R.id.intent_to_common2); 68 | common2.setOnClickListener(this); 69 | 70 | Switch aSwitch = findViewById(R.id.runtime_switch); 71 | 72 | aSwitch.setChecked(SpConfig.getLoadRuntime()); 73 | setCheck(SpConfig.getLoadRuntime()); 74 | aSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> { 75 | SpConfig.setLoadRuntime(isChecked); 76 | setCheck(isChecked); 77 | }); 78 | 79 | JsLoaderUtil.jsState.bundleName = "business3"; 80 | JsLoaderUtil.load(getApplication()); 81 | } 82 | 83 | private void setCheck(boolean isChecked) { 84 | TextView rtText = findViewById(R.id.runtime_text); 85 | if (isChecked) { 86 | rtText.setText("LoadRuntime--on"); 87 | } else { 88 | rtText.setText("LoadRuntime-off"); 89 | } 90 | } 91 | 92 | 93 | @Override 94 | public void onClick(View v) { 95 | switch (v.getId()) { 96 | case R.id.business1: 97 | windowIntent(Business1Activity.class); 98 | break; 99 | case R.id.business2: 100 | JsLoaderUtil.jsState.isFilePrior = true; 101 | JsLoaderUtil.setJsBundle("business2", "App2"); 102 | windowIntent(Business2Activity.class); 103 | break; 104 | case R.id.business3: 105 | windowIntent(Business3Activity.class); 106 | break; 107 | case R.id.business4: 108 | JsLoaderUtil.setJsBundle("business4", "App4"); 109 | JsLoaderUtil.load(getApplication(), () -> windowIntent(Business4Activity.class)); 110 | break; 111 | case R.id.intent_to_common1: 112 | JsLoaderUtil.addBundles(getApplication(), 113 | Arrays.asList("business1", "business2", "business3", "business4"), 114 | () -> configComponentName(Common1Activity.class)); 115 | break; 116 | case R.id.intent_to_common2: 117 | JsLoaderUtil.jsState.neededBundle.addAll(Arrays.asList("business1", "business2", "business3", "business4")); 118 | configComponentName(Common2Activity.class); 119 | break; 120 | default: 121 | break; 122 | } 123 | } 124 | 125 | 126 | private void configComponentName(Class goalClass) { 127 | String text; 128 | if (goalClass == Common1Activity.class) { 129 | text = common1.getText().toString(); 130 | } else { 131 | text = common2.getText().toString(); 132 | } 133 | index = Integer.parseInt(text.substring(text.length() - 1)) - 1; 134 | 135 | if (index == 4) { 136 | index = 1; 137 | } else { 138 | index++; 139 | } 140 | JsLoaderUtil.jsState.componentName = "App" + index; 141 | windowIntent(goalClass); 142 | new Handler().postDelayed(() -> { 143 | int show = 0; 144 | if (index == 4) { 145 | show = 1; 146 | } else { 147 | show = index + 1; 148 | } 149 | if (goalClass == Common1Activity.class) { 150 | common1.setText("提前loadBundle后跳转到同一个页面-Business" + show); 151 | } else { 152 | common2.setText("先设置bundle名称,进入时loadBundle-Business" + show); 153 | } 154 | 155 | }, 1000); 156 | } 157 | 158 | private void windowIntent(Class goalClass) { 159 | Intent intent = new Intent(this, goalClass); 160 | startActivity(intent); 161 | } 162 | 163 | @Override 164 | protected void onDestroy() { 165 | super.onDestroy(); 166 | System.exit(0); 167 | 168 | } 169 | } 170 | -------------------------------------------------------------------------------- /android/app/src/main/java/com/yxyhail/metroexample/MainApplication.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 yxyhail 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yxyhail.metroexample; 18 | 19 | import android.app.Application; 20 | import android.content.Context; 21 | 22 | import com.facebook.react.ReactApplication; 23 | import com.facebook.react.ReactNativeHost; 24 | import com.facebook.react.ReactPackage; 25 | import com.facebook.react.shell.MainReactPackage; 26 | import com.facebook.soloader.SoLoader; 27 | import com.yxyhail.metroexample.react.JsLoaderUtil; 28 | import com.yxyhail.metroexample.utils.SpConfig; 29 | 30 | import java.util.Arrays; 31 | import java.util.List; 32 | 33 | import javax.annotation.Nullable; 34 | 35 | public class MainApplication extends Application implements ReactApplication { 36 | 37 | private static Application app; 38 | 39 | private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { 40 | @Override 41 | public boolean getUseDeveloperSupport() { 42 | JsLoaderUtil.jsState.isDev = SpConfig.getLoadRuntime(); 43 | return SpConfig.getLoadRuntime(); 44 | } 45 | 46 | 47 | @Override 48 | protected List getPackages() { 49 | return Arrays.asList( 50 | new MainReactPackage()); 51 | } 52 | 53 | @Nullable 54 | @Override 55 | protected String getJSBundleFile() { 56 | return JsLoaderUtil.getBasicBundle(getApplication(), getBundleAssetName()); 57 | } 58 | 59 | @Nullable 60 | @Override 61 | protected String getBundleAssetName() { 62 | return "basics.android.bundle"; 63 | } 64 | 65 | @Override 66 | protected String getJSMainModuleName() { 67 | return "index"; 68 | } 69 | }; 70 | 71 | @Override 72 | public ReactNativeHost getReactNativeHost() { 73 | return mReactNativeHost; 74 | } 75 | 76 | @Override 77 | public void onCreate() { 78 | super.onCreate(); 79 | app = this; 80 | SoLoader.init(this, /* native exopackage */ false); 81 | } 82 | 83 | public static Application getApp() { 84 | return app; 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /android/app/src/main/java/com/yxyhail/metroexample/react/BaseReactActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 yxyhail 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yxyhail.metroexample.react; 18 | 19 | import android.os.Bundle; 20 | import android.text.TextUtils; 21 | 22 | import com.facebook.react.ReactActivity; 23 | import com.facebook.react.ReactActivityDelegate; 24 | import com.yxyhail.metroexample.react.JsLoaderUtil; 25 | 26 | import javax.annotation.Nullable; 27 | 28 | public class BaseReactActivity extends ReactActivity { 29 | @Override 30 | protected ReactActivityDelegate createReactActivityDelegate() { 31 | String localBundleName = getBundleName(); 32 | if (!TextUtils.isEmpty(localBundleName)) { 33 | JsLoaderUtil.jsState.bundleName = localBundleName; 34 | } 35 | return new ReactActivityDelegate(this, getMainComponentName()) { 36 | @Override 37 | protected void onCreate(Bundle savedInstanceState) { 38 | JsLoaderUtil.load(getApplication(), 39 | () -> super.onCreate(savedInstanceState)); 40 | } 41 | }; 42 | } 43 | 44 | 45 | @Nullable 46 | @Override 47 | protected String getMainComponentName() { 48 | return JsLoaderUtil.jsState.componentName; 49 | } 50 | 51 | protected String getBundleName() { 52 | return ""; 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /android/app/src/main/java/com/yxyhail/metroexample/react/JsLoaderUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 yxyhail 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yxyhail.metroexample.react; 18 | 19 | import android.app.Application; 20 | import android.support.annotation.Nullable; 21 | import android.text.TextUtils; 22 | import android.util.SparseArray; 23 | 24 | import com.facebook.react.ReactApplication; 25 | import com.facebook.react.ReactInstanceManager; 26 | import com.facebook.react.bridge.CatalystInstance; 27 | import com.facebook.react.bridge.ReactContext; 28 | import com.facebook.react.modules.appregistry.AppRegistry; 29 | 30 | import java.io.File; 31 | import java.util.ArrayList; 32 | import java.util.List; 33 | 34 | public class JsLoaderUtil { 35 | public static final JsState jsState = new JsState(); 36 | 37 | public static void load(Application application) { 38 | load(application, null); 39 | } 40 | 41 | public static void load(Application application, ReactContextCallBack callBack) { 42 | if (jsState.isDev) { 43 | if (callBack != null) callBack.onInitialized(); 44 | return; 45 | } 46 | createReactContext(application, () -> { 47 | loadBundle(application); 48 | if (callBack != null) callBack.onInitialized(); 49 | }); 50 | } 51 | 52 | 53 | public interface ReactContextCallBack { 54 | void onInitialized(); 55 | } 56 | 57 | public static void createReactContext(Application application, ReactContextCallBack callBack) { 58 | if (jsState.isDev) { 59 | if(callBack != null) callBack.onInitialized(); 60 | return; 61 | } 62 | final ReactInstanceManager manager = getReactIM(application); 63 | if (!manager.hasStartedCreatingInitialContext()) { 64 | manager.addReactInstanceEventListener(new ReactInstanceManager.ReactInstanceEventListener() { 65 | @Override 66 | public void onReactContextInitialized(ReactContext context) { 67 | if (callBack != null) callBack.onInitialized(); 68 | manager.removeReactInstanceEventListener(this); 69 | } 70 | }); 71 | manager.createReactContextInBackground(); 72 | } else { 73 | if (callBack != null) callBack.onInitialized(); 74 | } 75 | } 76 | 77 | public static ReactInstanceManager getReactIM(Application application) { 78 | return ((ReactApplication) application).getReactNativeHost().getReactInstanceManager(); 79 | } 80 | 81 | @Nullable 82 | public static CatalystInstance getCatalyst(Application application) { 83 | ReactInstanceManager manager = getReactIM(application); 84 | if (manager == null) { 85 | return null; 86 | } 87 | ReactContext context = manager.getCurrentReactContext(); 88 | if (context == null) { 89 | return null; 90 | } 91 | return context.getCatalystInstance(); 92 | } 93 | 94 | public static void loadBundle(Application application) { 95 | if (jsState.neededBundle.size() > 0) { 96 | for (int i = 0; i < jsState.neededBundle.size(); i++) { 97 | String name = jsState.neededBundle.get(i) + jsState.bundleSuffix; 98 | File file = new File(jsState.filePath + name); 99 | if (file.exists() && jsState.isFilePrior) { 100 | fromFile(application, name, file.getAbsolutePath()); 101 | } else { 102 | fromAssets(application, name); 103 | } 104 | } 105 | } else { 106 | String name = jsState.bundleName + jsState.bundleSuffix; 107 | File file = new File(jsState.filePath + File.separator + name); 108 | if (file.exists() && jsState.isFilePrior) { 109 | fromFile(application, name, file.getAbsolutePath()); 110 | } else { 111 | fromAssets(application, name); 112 | } 113 | } 114 | 115 | } 116 | 117 | 118 | public static void fromAssets(Application application, String bundleName) { 119 | fromAssets(application, bundleName, jsState.isSync); 120 | } 121 | 122 | public static void fromAssets(Application application, String bundleName, boolean isSync) { 123 | if (hasBundle(bundleName) || JsLoaderUtil.jsState.isDev) { 124 | return; 125 | } 126 | String source = bundleName; 127 | if (!bundleName.startsWith("assets://")) { 128 | source = "assets://" + bundleName; 129 | } 130 | if (!source.endsWith(jsState.bundleSuffix)) { 131 | source = source + jsState.bundleSuffix; 132 | } 133 | CatalystInstance catalyst = getCatalyst(application); 134 | try { 135 | if (catalyst != null) { 136 | catalyst.loadScriptFromAssets(application.getAssets(), source, isSync); 137 | addBundle(bundleName); 138 | } 139 | } catch (Exception e) { 140 | e.printStackTrace(); 141 | } 142 | } 143 | 144 | public static void fromFile(Application application, String bundleName, String sourceUrl) { 145 | fromFile(application, bundleName, sourceUrl, jsState.isSync); 146 | } 147 | 148 | public static void fromFile(Application application, String bundleName, String sourceUrl, boolean isSync) { 149 | if (hasBundle(sourceUrl) || JsLoaderUtil.jsState.isDev) { 150 | return; 151 | } 152 | if (TextUtils.isEmpty(jsState.filePath)) { 153 | setDefaultFileDir(application); 154 | } 155 | String bundleDir = jsState.filePath; 156 | 157 | CatalystInstance catalyst = getCatalyst(application); 158 | try { 159 | if (catalyst != null) { 160 | catalyst.loadScriptFromFile(bundleDir + File.separator + bundleName, sourceUrl, isSync); 161 | addBundle(sourceUrl); 162 | } 163 | } catch (Exception e) { 164 | e.printStackTrace(); 165 | } 166 | } 167 | 168 | 169 | public static String getBasicBundle(Application application, String bundleName) { 170 | if (jsState.isFilePrior) { 171 | String path =getReactDir(application) + bundleName; 172 | if(new File(path).exists()){ 173 | return path; 174 | }else{ 175 | return null; 176 | } 177 | } else { 178 | return null; 179 | } 180 | } 181 | 182 | private static String getReactDir(Application application){ 183 | return application.getFilesDir()+ File.separator+jsState.reactDir+File.separator; 184 | } 185 | 186 | public static void setDefaultFileDir(Application application) { 187 | File scriptFile = new File(getReactDir(application)); 188 | jsState.filePath = scriptFile.getAbsolutePath(); 189 | } 190 | 191 | public static void addBundles(Application application, List bundlesName, ReactContextCallBack callBack) { 192 | jsState.neededBundle.addAll(bundlesName); 193 | load(application, callBack); 194 | } 195 | 196 | 197 | private static void addBundle(String bundle) { 198 | int index = jsState.loadedBundle.size(); 199 | jsState.loadedBundle.put(index, bundle); 200 | } 201 | 202 | private static boolean hasBundle(String bundle) { 203 | return jsState.loadedBundle.indexOfValue(bundle) != -1; 204 | } 205 | 206 | public static void clearBundle() { 207 | jsState.loadedBundle.clear(); 208 | } 209 | 210 | public static void setJsBundle(String bundleName, String componentName) { 211 | jsState.bundleName = bundleName; 212 | jsState.componentName = componentName; 213 | } 214 | 215 | public static class JsState { 216 | public boolean isDev = false; 217 | boolean isSync = false; 218 | public boolean isFilePrior = true; 219 | public String filePath = ""; 220 | public String reactDir = "bundle"; 221 | public String bundleSuffix = ".android.bundle"; 222 | public String bundleName = ""; 223 | public String componentName = ""; 224 | public int index = 1; 225 | 226 | private SparseArray loadedBundle = new SparseArray<>(); 227 | public List neededBundle = new ArrayList<>(); 228 | } 229 | 230 | } 231 | -------------------------------------------------------------------------------- /android/app/src/main/java/com/yxyhail/metroexample/ui/Business1Activity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 yxyhail 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yxyhail.metroexample.ui; 18 | 19 | import com.yxyhail.metroexample.react.BaseReactActivity; 20 | import com.yxyhail.metroexample.react.JsLoaderUtil; 21 | 22 | import javax.annotation.Nullable; 23 | 24 | public class Business1Activity extends BaseReactActivity { 25 | @Override 26 | protected String getBundleName() { 27 | JsLoaderUtil.jsState.isFilePrior = false; 28 | return "business1"; 29 | } 30 | 31 | @Nullable 32 | @Override 33 | protected String getMainComponentName() { 34 | return "App1"; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /android/app/src/main/java/com/yxyhail/metroexample/ui/Business2Activity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 yxyhail 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yxyhail.metroexample.ui; 18 | 19 | import com.yxyhail.metroexample.react.BaseReactActivity; 20 | 21 | public class Business2Activity extends BaseReactActivity { 22 | } 23 | -------------------------------------------------------------------------------- /android/app/src/main/java/com/yxyhail/metroexample/ui/Business3Activity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 yxyhail 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yxyhail.metroexample.ui; 18 | 19 | import com.facebook.react.ReactActivity; 20 | 21 | 22 | public class Business3Activity extends ReactActivity { 23 | @Override 24 | protected String getMainComponentName() { 25 | return "App3"; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /android/app/src/main/java/com/yxyhail/metroexample/ui/Business4Activity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 yxyhail 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yxyhail.metroexample.ui; 18 | 19 | import com.facebook.react.ReactActivity; 20 | import com.yxyhail.metroexample.react.JsLoaderUtil; 21 | 22 | public class Business4Activity extends ReactActivity { 23 | 24 | @Override 25 | protected String getMainComponentName() { 26 | return JsLoaderUtil.jsState.componentName; 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /android/app/src/main/java/com/yxyhail/metroexample/ui/Common1Activity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 yxyhail 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yxyhail.metroexample.ui; 18 | 19 | import com.facebook.react.ReactActivity; 20 | import com.yxyhail.metroexample.react.JsLoaderUtil; 21 | 22 | public class Common1Activity extends ReactActivity { 23 | 24 | @Override 25 | protected String getMainComponentName() { 26 | return JsLoaderUtil.jsState.componentName; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /android/app/src/main/java/com/yxyhail/metroexample/ui/Common2Activity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 yxyhail 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yxyhail.metroexample.ui; 18 | 19 | import com.yxyhail.metroexample.react.BaseReactActivity; 20 | 21 | public class Common2Activity extends BaseReactActivity { 22 | 23 | // @Override 24 | // public void onWindowFocusChanged(boolean hasFocus) { 25 | // super.onWindowFocusChanged(hasFocus); 26 | // if (hasFocus) { 27 | // if (SpConfig.getIndex() != -1) { 28 | // SpConfig.setIndex(-1); 29 | // JsLoaderUtil.jsState.componentName = "App2"; 30 | //// JsLoaderUtil.jsState.isFilePrior = false; 31 | // recreate(); 32 | // } 33 | // } 34 | // } 35 | } 36 | -------------------------------------------------------------------------------- /android/app/src/main/java/com/yxyhail/metroexample/utils/FileUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 yxyhail 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yxyhail.metroexample.utils; 18 | 19 | import android.content.Context; 20 | 21 | import java.io.File; 22 | import java.io.FileOutputStream; 23 | import java.io.IOException; 24 | import java.io.InputStream; 25 | import java.io.OutputStream; 26 | import java.util.Enumeration; 27 | import java.util.zip.ZipEntry; 28 | import java.util.zip.ZipFile; 29 | 30 | 31 | public class FileUtil { 32 | 33 | public static File copyAssetsFile(Context context, String fileName) { 34 | OutputStream outputStream = null; 35 | InputStream inputStream = null; 36 | File file = new File(context.getFilesDir(), fileName); 37 | try { 38 | inputStream =context.getAssets().open(fileName); 39 | outputStream = new FileOutputStream(file); 40 | int len; 41 | byte[] buffer = new byte[1024]; 42 | while ( (len = inputStream.read(buffer)) != -1 ) { 43 | outputStream.write(buffer, 0, len); 44 | } 45 | } catch ( IOException e ) { 46 | e.printStackTrace(); 47 | } finally { 48 | try { 49 | inputStream.close(); 50 | outputStream.close(); 51 | } catch ( Exception e ) { 52 | e.printStackTrace(); 53 | } 54 | } 55 | return file; 56 | } 57 | 58 | 59 | public static void unZip(File srcFile, String destDirPath) throws RuntimeException { 60 | if (!srcFile.exists()) { 61 | return; 62 | } 63 | ZipFile zipFile = null; 64 | try { 65 | zipFile = new ZipFile(srcFile); 66 | Enumeration entries = zipFile.entries(); 67 | while (entries.hasMoreElements()) { 68 | ZipEntry entry = (ZipEntry) entries.nextElement(); 69 | if (entry.isDirectory()) { 70 | String dirPath = destDirPath + "/" + entry.getName(); 71 | File dir = new File(dirPath); 72 | dir.mkdirs(); 73 | } else { 74 | File targetFile = new File(destDirPath + "/" + entry.getName()); 75 | if (!targetFile.getParentFile().exists()) { 76 | targetFile.getParentFile().mkdirs(); 77 | } 78 | targetFile.createNewFile(); 79 | InputStream is = zipFile.getInputStream(entry); 80 | FileOutputStream fos = new FileOutputStream(targetFile); 81 | int len; 82 | byte[] buf = new byte[2048]; 83 | while ((len = is.read(buf)) != -1) { 84 | fos.write(buf, 0, len); 85 | } 86 | fos.close(); 87 | is.close(); 88 | } 89 | } 90 | long end = System.currentTimeMillis(); 91 | } catch (Exception e) { 92 | e.printStackTrace(); 93 | } finally { 94 | if (zipFile != null) { 95 | try { 96 | zipFile.close(); 97 | } catch (IOException e) { 98 | e.printStackTrace(); 99 | } 100 | } 101 | } 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /android/app/src/main/java/com/yxyhail/metroexample/utils/SpConfig.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * Copyright 2019 yxyhail 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | package com.yxyhail.metroexample.utils; 19 | 20 | import android.content.Context; 21 | import android.content.SharedPreferences; 22 | 23 | import com.yxyhail.metroexample.MainApplication; 24 | 25 | public class SpConfig { 26 | 27 | private SpConfig() { 28 | } 29 | 30 | public static void setLoadRuntime(boolean isLoadRuntime) { 31 | saveBoolean("isLoadRuntime", isLoadRuntime); 32 | } 33 | 34 | public static boolean getLoadRuntime() { 35 | return getBoolean("isLoadRuntime"); 36 | } 37 | 38 | public static void setIndex(int index) { 39 | saveInt("index", index); 40 | } 41 | 42 | public static int getIndex() { 43 | return getInt("index"); 44 | } 45 | 46 | 47 | private static SharedPreferences getSp() { 48 | return MainApplication.getApp().getSharedPreferences("colonel_tool", Context.MODE_PRIVATE); 49 | } 50 | 51 | 52 | private static String getString(String key) { 53 | return getSp().getString(key, ""); 54 | } 55 | 56 | private static int getInt(String key) { 57 | return getSp().getInt(key, 0); 58 | } 59 | 60 | private static boolean getBoolean(String key) { 61 | return getSp().getBoolean(key, false); 62 | } 63 | 64 | private static long getLong(String key) { 65 | return getSp().getLong(key, 0); 66 | } 67 | 68 | private static void saveString(String key, String value) { 69 | getSp().edit().putString(key, value).apply(); 70 | } 71 | 72 | private static void saveInt(String key, int value) { 73 | getSp().edit().putInt(key, value).apply(); 74 | } 75 | 76 | private static void saveBoolean(String key, boolean value) { 77 | getSp().edit().putBoolean(key, value).apply(); 78 | } 79 | 80 | private static void saveLong(String key, long value) { 81 | getSp().edit().putLong(key, value).apply(); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /android/app/src/main/kotlin/com/yxyhail/metroexample/MainActivity.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 yxyhail 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yxyhail.metroexample 18 | 19 | import android.content.Intent 20 | import android.os.Bundle 21 | import android.os.Handler 22 | import android.support.v7.app.AppCompatActivity 23 | import android.view.View 24 | import java.util.Arrays 25 | 26 | import com.yxyhail.metroexample.react.JsLoaderUtil 27 | import com.yxyhail.metroexample.ui.Business1Activity 28 | import com.yxyhail.metroexample.ui.Business2Activity 29 | import com.yxyhail.metroexample.ui.Business3Activity 30 | import com.yxyhail.metroexample.ui.Business4Activity 31 | import com.yxyhail.metroexample.ui.Common1Activity 32 | import com.yxyhail.metroexample.ui.Common2Activity 33 | import com.yxyhail.metroexample.utils.FileUtil 34 | import com.yxyhail.metroexample.utils.SpConfig 35 | import kotlinx.android.synthetic.main.activity_main.* 36 | 37 | 38 | class MainActivity : AppCompatActivity(), View.OnClickListener { 39 | private var index = 0 40 | 41 | override fun onCreate(savedInstanceState: Bundle?) { 42 | super.onCreate(savedInstanceState) 43 | 44 | setContentView(R.layout.activity_main) 45 | business1.setOnClickListener(this) 46 | business2.setOnClickListener(this) 47 | business3.setOnClickListener(this) 48 | business4.setOnClickListener(this) 49 | JsLoaderUtil.jsState.isFilePrior = true 50 | 51 | //模拟下载Bundle到本地File 52 | JsLoaderUtil.setDefaultFileDir(application) 53 | val file = FileUtil.copyAssetsFile(this, "bundle.zip") 54 | FileUtil.unZip(file, filesDir.absolutePath) 55 | 56 | SpConfig.index = 0 57 | 58 | intent_to_common1.setOnClickListener(this) 59 | intent_to_common2.setOnClickListener(this) 60 | 61 | 62 | runtime_switch.isChecked = SpConfig.loadRuntime 63 | setCheck(SpConfig.loadRuntime) 64 | runtime_switch.setOnCheckedChangeListener { _, isChecked -> 65 | SpConfig.loadRuntime = isChecked 66 | setCheck(isChecked) 67 | } 68 | 69 | JsLoaderUtil.jsState.bundleName = "business3" 70 | JsLoaderUtil.load(application) 71 | } 72 | 73 | private fun setCheck(isChecked: Boolean) { 74 | runtime_text.text = if (isChecked) "LoadRuntime--on" else "LoadRuntime-off" 75 | } 76 | 77 | 78 | override fun onClick(v: View) { 79 | when (v.id) { 80 | R.id.business1 -> windowIntent(Business1Activity::class.java) 81 | R.id.business2 -> { 82 | JsLoaderUtil.jsState.isFilePrior = true 83 | JsLoaderUtil.setJsBundle("business2", "App2") 84 | windowIntent(Business2Activity::class.java) 85 | } 86 | R.id.business3 -> windowIntent(Business3Activity::class.java) 87 | R.id.business4 -> { 88 | JsLoaderUtil.setJsBundle("business4", "App4") 89 | JsLoaderUtil.load(application) { windowIntent(Business4Activity::class.java) } 90 | } 91 | R.id.intent_to_common1 -> 92 | JsLoaderUtil.addBundles(application, 93 | Arrays.asList("business1", "business2", "business3", "business4")) { 94 | configComponentName(Common1Activity::class.java) 95 | } 96 | R.id.intent_to_common2 -> { 97 | JsLoaderUtil.jsState.neededBundle.addAll(Arrays.asList("business1", "business2", "business3", "business4")) 98 | configComponentName(Common2Activity::class.java) 99 | } 100 | else -> { 101 | } 102 | } 103 | } 104 | 105 | 106 | private fun configComponentName(goalClass: Class<*>) { 107 | val text = if (goalClass == Common1Activity::class.java) { 108 | intent_to_common1.text.toString() 109 | } else { 110 | intent_to_common2.text.toString() 111 | } 112 | index = text.substring(text.length - 1).toInt() - 1 113 | 114 | if (index == 4) index = 1 else index++ 115 | 116 | JsLoaderUtil.jsState.componentName = "App$index" 117 | windowIntent(goalClass) 118 | Handler().postDelayed({ 119 | val show = if (index == 4) { 120 | 1 121 | } else { 122 | index + 1 123 | } 124 | if (goalClass == Common1Activity::class.java) { 125 | intent_to_common1.text = "提前loadBundle后跳转到同一个页面-Business$show" 126 | } else { 127 | intent_to_common2.text = "先设置bundle名称,进入时loadBundle-Business$show" 128 | } 129 | }, 1000) 130 | } 131 | 132 | private fun windowIntent(goalClass: Class<*>) { 133 | val intent = Intent(this, goalClass) 134 | startActivity(intent) 135 | } 136 | 137 | override fun onDestroy() { 138 | super.onDestroy() 139 | System.exit(0) 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /android/app/src/main/kotlin/com/yxyhail/metroexample/MainApplication.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 yxyhail 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yxyhail.metroexample 18 | 19 | import android.app.Application 20 | 21 | import com.facebook.react.ReactApplication 22 | import com.facebook.react.ReactNativeHost 23 | import com.facebook.react.ReactPackage 24 | import com.facebook.react.shell.MainReactPackage 25 | import com.facebook.soloader.SoLoader 26 | 27 | import java.util.Arrays 28 | 29 | import com.yxyhail.metroexample.react.JsLoaderUtil 30 | import com.yxyhail.metroexample.utils.SpConfig 31 | 32 | class MainApplication : Application(), ReactApplication { 33 | 34 | private val mReactNativeHost = object : ReactNativeHost(this) { 35 | override fun getUseDeveloperSupport(): Boolean { 36 | JsLoaderUtil.jsState.isDev = SpConfig.loadRuntime 37 | return SpConfig.loadRuntime 38 | } 39 | 40 | 41 | override fun getPackages(): List { 42 | return Arrays.asList( 43 | MainReactPackage()) 44 | } 45 | 46 | override fun getJSBundleFile(): String? { 47 | return JsLoaderUtil.getBasicBundle(application, bundleAssetName!!) 48 | } 49 | 50 | override fun getBundleAssetName(): String? { 51 | return "basics.android.bundle" 52 | } 53 | 54 | override fun getJSMainModuleName(): String { 55 | return "index" 56 | } 57 | } 58 | 59 | override fun getReactNativeHost(): ReactNativeHost { 60 | return mReactNativeHost 61 | } 62 | 63 | override fun onCreate() { 64 | super.onCreate() 65 | app = this 66 | SoLoader.init(this, /* native exopackage */ false) 67 | } 68 | 69 | companion object { 70 | var app: Application? = null 71 | private set 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /android/app/src/main/kotlin/com/yxyhail/metroexample/react/BaseReactActivity.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 yxyhail 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yxyhail.metroexample.react 18 | 19 | import android.os.Bundle 20 | import android.text.TextUtils 21 | 22 | import com.facebook.react.ReactActivity 23 | import com.facebook.react.ReactActivityDelegate 24 | 25 | open class BaseReactActivity : ReactActivity() { 26 | 27 | protected open val bundleName: String 28 | get() = "" 29 | 30 | override fun createReactActivityDelegate(): ReactActivityDelegate { 31 | val localBundleName = bundleName 32 | if (!TextUtils.isEmpty(localBundleName)) { 33 | JsLoaderUtil.jsState.bundleName = localBundleName 34 | } 35 | return object : ReactActivityDelegate(this, mainComponentName) { 36 | override fun onCreate(savedInstanceState: Bundle?) { 37 | JsLoaderUtil.load(application) { super.onCreate(savedInstanceState) } 38 | } 39 | } 40 | } 41 | 42 | 43 | override fun getMainComponentName(): String? { 44 | return JsLoaderUtil.jsState.componentName 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /android/app/src/main/kotlin/com/yxyhail/metroexample/react/JsLoaderUtil.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 yxyhail 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yxyhail.metroexample.react 18 | 19 | import android.app.Application 20 | import android.text.TextUtils 21 | import android.util.SparseArray 22 | 23 | import com.facebook.react.ReactApplication 24 | import com.facebook.react.ReactInstanceManager 25 | import com.facebook.react.bridge.CatalystInstance 26 | import com.facebook.react.bridge.ReactContext 27 | 28 | import java.io.File 29 | import java.util.ArrayList 30 | 31 | object JsLoaderUtil { 32 | val jsState = JsState() 33 | 34 | @JvmOverloads 35 | fun load(application: Application, callBack: () -> Unit = {}) { 36 | if (jsState.isDev) { 37 | callBack() 38 | return 39 | } 40 | createReactContext(application) { 41 | loadBundle(application) 42 | callBack() 43 | } 44 | } 45 | 46 | 47 | private fun createReactContext(application: Application, callBack: () -> Unit = {}) { 48 | if (jsState.isDev) { 49 | callBack() 50 | return 51 | } 52 | val manager = getReactIM(application) 53 | if (!manager!!.hasStartedCreatingInitialContext()) { 54 | manager.addReactInstanceEventListener(object : ReactInstanceManager.ReactInstanceEventListener { 55 | override fun onReactContextInitialized(context: ReactContext) { 56 | callBack() 57 | manager.removeReactInstanceEventListener(this) 58 | } 59 | }) 60 | manager.createReactContextInBackground() 61 | } else { 62 | callBack() 63 | } 64 | } 65 | 66 | private fun getReactIM(application: Application): ReactInstanceManager? { 67 | return (application as ReactApplication).reactNativeHost.reactInstanceManager 68 | } 69 | 70 | private fun getCatalyst(application: Application): CatalystInstance? { 71 | val manager = getReactIM(application) ?: return null 72 | val context = manager.currentReactContext ?: return null 73 | return context.catalystInstance 74 | } 75 | 76 | private fun loadBundle(application: Application) { 77 | if (jsState.neededBundle.size > 0) { 78 | for (i in jsState.neededBundle.indices) { 79 | val name = jsState.neededBundle[i] + jsState.bundleSuffix 80 | val file = File(jsState.filePath + name) 81 | if (file.exists() && jsState.isFilePrior) { 82 | fromFile(application, name, file.absolutePath) 83 | } else { 84 | fromAssets(application, name) 85 | } 86 | } 87 | } else { 88 | val name = jsState.bundleName + jsState.bundleSuffix 89 | val file = File(jsState.filePath + File.separator + name) 90 | if (file.exists() && jsState.isFilePrior) { 91 | fromFile(application, name, file.absolutePath) 92 | } else { 93 | fromAssets(application, name) 94 | } 95 | } 96 | 97 | } 98 | 99 | @JvmOverloads 100 | fun fromAssets(application: Application, bundleName: String, isSync: Boolean = jsState.isSync) { 101 | if (hasBundle(bundleName) || JsLoaderUtil.jsState.isDev) { 102 | return 103 | } 104 | var source = bundleName 105 | if (!bundleName.startsWith("assets://")) { 106 | source = "assets://$bundleName" 107 | } 108 | if (!source.endsWith(jsState.bundleSuffix)) { 109 | source = source + jsState.bundleSuffix 110 | } 111 | val catalyst = getCatalyst(application) 112 | try { 113 | if (catalyst != null) { 114 | catalyst.loadScriptFromAssets(application.assets, source, isSync) 115 | addBundle(bundleName) 116 | } 117 | } catch (e: Exception) { 118 | e.printStackTrace() 119 | } 120 | 121 | } 122 | 123 | @JvmOverloads 124 | fun fromFile(application: Application, bundleName: String, sourceUrl: String, isSync: Boolean = jsState.isSync) { 125 | if (hasBundle(sourceUrl) || JsLoaderUtil.jsState.isDev) { 126 | return 127 | } 128 | if (TextUtils.isEmpty(jsState.filePath)) { 129 | setDefaultFileDir(application) 130 | } 131 | val bundleDir = jsState.filePath 132 | 133 | val catalyst = getCatalyst(application) 134 | try { 135 | if (catalyst != null) { 136 | catalyst.loadScriptFromFile(bundleDir + File.separator + bundleName, sourceUrl, isSync) 137 | addBundle(sourceUrl) 138 | } 139 | } catch (e: Exception) { 140 | e.printStackTrace() 141 | } 142 | 143 | } 144 | 145 | 146 | fun getBasicBundle(application: Application, bundleName: String): String? { 147 | return if (!jsState.isFilePrior) { 148 | null 149 | } else { 150 | val path = getReactDir(application) + bundleName 151 | if (File(path).exists()) { 152 | path 153 | } else { 154 | null 155 | } 156 | } 157 | } 158 | 159 | private fun getReactDir(application: Application): String { 160 | return application.filesDir.toString() + File.separator + jsState.reactDir + File.separator 161 | } 162 | 163 | fun setDefaultFileDir(application: Application) { 164 | val scriptFile = File(getReactDir(application)) 165 | jsState.filePath = scriptFile.absolutePath 166 | } 167 | 168 | fun addBundles(application: Application, bundlesName: List, callBack: () -> Unit = {}) { 169 | jsState.neededBundle.addAll(bundlesName) 170 | load(application, callBack) 171 | } 172 | 173 | 174 | private fun addBundle(bundle: String) { 175 | val index = jsState.loadedBundle.size() 176 | jsState.loadedBundle.put(index, bundle) 177 | } 178 | 179 | private fun hasBundle(bundle: String): Boolean { 180 | return jsState.loadedBundle.indexOfValue(bundle) != -1 181 | } 182 | 183 | fun clearBundle() { 184 | jsState.loadedBundle.clear() 185 | } 186 | 187 | fun setJsBundle(bundleName: String, componentName: String) { 188 | jsState.bundleName = bundleName 189 | jsState.componentName = componentName 190 | } 191 | 192 | class JsState { 193 | var isDev = false 194 | internal var isSync = false 195 | var isFilePrior = true 196 | var filePath = "" 197 | var reactDir = "bundle" 198 | var bundleSuffix = ".android.bundle" 199 | var bundleName = "" 200 | var componentName = "" 201 | var index = 1 202 | 203 | val loadedBundle = SparseArray() 204 | var neededBundle: MutableList = ArrayList() 205 | } 206 | 207 | } 208 | -------------------------------------------------------------------------------- /android/app/src/main/kotlin/com/yxyhail/metroexample/ui/Business1Activity.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 yxyhail 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yxyhail.metroexample.ui 18 | 19 | import com.yxyhail.metroexample.react.BaseReactActivity 20 | import com.yxyhail.metroexample.react.JsLoaderUtil 21 | 22 | class Business1Activity : BaseReactActivity() { 23 | override val bundleName: String 24 | get() { 25 | JsLoaderUtil.jsState.isFilePrior = false 26 | return "business1" 27 | } 28 | 29 | override fun getMainComponentName(): String? { 30 | return "App1" 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /android/app/src/main/kotlin/com/yxyhail/metroexample/ui/Business2Activity.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 yxyhail 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yxyhail.metroexample.ui 18 | 19 | import com.yxyhail.metroexample.react.BaseReactActivity 20 | 21 | class Business2Activity : BaseReactActivity() 22 | -------------------------------------------------------------------------------- /android/app/src/main/kotlin/com/yxyhail/metroexample/ui/Business3Activity.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 yxyhail 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yxyhail.metroexample.ui 18 | 19 | import com.facebook.react.ReactActivity 20 | 21 | 22 | class Business3Activity : ReactActivity() { 23 | 24 | override fun getMainComponentName(): String? { 25 | return "App3" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /android/app/src/main/kotlin/com/yxyhail/metroexample/ui/Business4Activity.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 yxyhail 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yxyhail.metroexample.ui 18 | 19 | import com.facebook.react.ReactActivity 20 | 21 | import com.yxyhail.metroexample.react.JsLoaderUtil 22 | 23 | class Business4Activity : ReactActivity() { 24 | 25 | override fun getMainComponentName(): String? { 26 | return JsLoaderUtil.jsState.componentName 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /android/app/src/main/kotlin/com/yxyhail/metroexample/ui/Common1Activity.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 yxyhail 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yxyhail.metroexample.ui 18 | 19 | import com.facebook.react.ReactActivity 20 | 21 | import com.yxyhail.metroexample.react.JsLoaderUtil 22 | 23 | class Common1Activity : ReactActivity() { 24 | 25 | override fun getMainComponentName(): String? { 26 | return JsLoaderUtil.jsState.componentName 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /android/app/src/main/kotlin/com/yxyhail/metroexample/ui/Common2Activity.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 yxyhail 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yxyhail.metroexample.ui 18 | 19 | import com.yxyhail.metroexample.react.BaseReactActivity 20 | import com.yxyhail.metroexample.react.JsLoaderUtil 21 | import com.yxyhail.metroexample.utils.SpConfig 22 | 23 | class Common2Activity : BaseReactActivity() { 24 | 25 | // override fun onWindowFocusChanged(hasFocus: Boolean) { 26 | // super.onWindowFocusChanged(hasFocus) 27 | // if (hasFocus) { 28 | // if (SpConfig.index != -1) { 29 | // SpConfig.index = -1 30 | // JsLoaderUtil.jsState.componentName = "App2" 31 | // // JsLoaderUtil.jsState.isFilePrior = false; 32 | // recreate() 33 | // } 34 | // } 35 | // } 36 | } 37 | -------------------------------------------------------------------------------- /android/app/src/main/kotlin/com/yxyhail/metroexample/utils/FileUtil.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 yxyhail 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yxyhail.metroexample.utils 18 | 19 | import android.content.Context 20 | 21 | import java.io.File 22 | import java.io.FileOutputStream 23 | import java.io.IOException 24 | import java.io.InputStream 25 | import java.io.OutputStream 26 | import java.util.Enumeration 27 | import java.util.zip.ZipEntry 28 | import java.util.zip.ZipFile 29 | 30 | 31 | object FileUtil { 32 | 33 | fun copyAssetsFile(context: Context, fileName: String): File { 34 | var outputStream: OutputStream? = null 35 | var inputStream: InputStream? = null 36 | val file = File(context.filesDir, fileName) 37 | try { 38 | inputStream = context.assets.open(fileName) 39 | outputStream = FileOutputStream(file) 40 | val buffer = ByteArray(1024) 41 | var len: Int = inputStream!!.read(buffer) 42 | while (len != -1) { 43 | outputStream.write(buffer, 0, len) 44 | len = inputStream.read(buffer) 45 | } 46 | } catch (e: IOException) { 47 | e.printStackTrace() 48 | } finally { 49 | try { 50 | inputStream!!.close() 51 | outputStream!!.close() 52 | } catch (e: Exception) { 53 | e.printStackTrace() 54 | } 55 | 56 | } 57 | return file 58 | } 59 | 60 | 61 | @Throws(RuntimeException::class) 62 | fun unZip(srcFile: File, destDirPath: String) { 63 | if (!srcFile.exists()) { 64 | return 65 | } 66 | var zipFile: ZipFile? = null 67 | try { 68 | zipFile = ZipFile(srcFile) 69 | val entries = zipFile.entries() 70 | while (entries.hasMoreElements()) { 71 | val entry = entries.nextElement() as ZipEntry 72 | if (entry.isDirectory) { 73 | val dirPath = destDirPath + "/" + entry.name 74 | val dir = File(dirPath) 75 | dir.mkdirs() 76 | } else { 77 | val targetFile = File(destDirPath + "/" + entry.name) 78 | if (!targetFile.parentFile.exists()) { 79 | targetFile.parentFile.mkdirs() 80 | } 81 | targetFile.createNewFile() 82 | val inputS = zipFile.getInputStream(entry) 83 | val fos = FileOutputStream(targetFile) 84 | val buf = ByteArray(2048) 85 | var len: Int = inputS.read(buf) 86 | while (len != -1) { 87 | fos.write(buf, 0, len) 88 | len = inputS.read(buf) 89 | } 90 | fos.close() 91 | inputS.close() 92 | } 93 | } 94 | } catch (e: Exception) { 95 | e.printStackTrace() 96 | } finally { 97 | if (zipFile != null) { 98 | try { 99 | zipFile.close() 100 | } catch (e: IOException) { 101 | e.printStackTrace() 102 | } 103 | 104 | } 105 | } 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /android/app/src/main/kotlin/com/yxyhail/metroexample/utils/SpConfig.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 yxyhail 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yxyhail.metroexample.utils 18 | 19 | import android.content.Context 20 | import android.content.SharedPreferences 21 | 22 | import com.yxyhail.metroexample.MainApplication 23 | 24 | object SpConfig { 25 | 26 | var loadRuntime: Boolean 27 | get() = getBoolean("isLoadRuntime") 28 | set(isLoadRuntime) = saveBoolean("isLoadRuntime", isLoadRuntime) 29 | 30 | var index: Int 31 | get() = getInt("index") 32 | set(index) = saveInt("index", index) 33 | 34 | 35 | 36 | 37 | private val sp: SharedPreferences 38 | get() = MainApplication.app!!.getSharedPreferences("colonel_tool", Context.MODE_PRIVATE) 39 | 40 | 41 | private fun getString(key: String): String? { 42 | return sp.getString(key, "") 43 | } 44 | 45 | private fun getInt(key: String): Int { 46 | return sp.getInt(key, 0) 47 | } 48 | 49 | private fun getBoolean(key: String): Boolean { 50 | return sp.getBoolean(key, false) 51 | } 52 | 53 | private fun getLong(key: String): Long { 54 | return sp.getLong(key, 0) 55 | } 56 | 57 | private fun saveString(key: String, value: String) { 58 | sp.edit().putString(key, value).apply() 59 | } 60 | 61 | private fun saveInt(key: String, value: Int) { 62 | sp.edit().putInt(key, value).apply() 63 | } 64 | 65 | private fun saveBoolean(key: String, value: Boolean) { 66 | sp.edit().putBoolean(key, value).apply() 67 | } 68 | 69 | private fun saveLong(key: String, value: Long) { 70 | sp.edit().putLong(key, value).apply() 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /android/app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 9 | 11 | 13 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /android/app/src/main/res/drawable/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 22 | 24 | 26 | 28 | 31 | 34 | 37 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /android/app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 23 | 24 | 35 | 36 | 47 | 48 | 59 | 60 | 61 | 72 | 73 | 84 | 85 | 96 | 97 | 102 | 103 | 111 | 112 | 121 | 122 | 123 | 124 | 125 | -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yxyhail/MetroExample/0180d2f08ae7849b6838aba379db1a4f69bc5109/android/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yxyhail/MetroExample/0180d2f08ae7849b6838aba379db1a4f69bc5109/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yxyhail/MetroExample/0180d2f08ae7849b6838aba379db1a4f69bc5109/android/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yxyhail/MetroExample/0180d2f08ae7849b6838aba379db1a4f69bc5109/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yxyhail/MetroExample/0180d2f08ae7849b6838aba379db1a4f69bc5109/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yxyhail/MetroExample/0180d2f08ae7849b6838aba379db1a4f69bc5109/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yxyhail/MetroExample/0180d2f08ae7849b6838aba379db1a4f69bc5109/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yxyhail/MetroExample/0180d2f08ae7849b6838aba379db1a4f69bc5109/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yxyhail/MetroExample/0180d2f08ae7849b6838aba379db1a4f69bc5109/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yxyhail/MetroExample/0180d2f08ae7849b6838aba379db1a4f69bc5109/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /android/app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | #097AFE 19 | -------------------------------------------------------------------------------- /android/app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | Metro 19 | 20 | -------------------------------------------------------------------------------- /android/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | 19 | 20 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /android/build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | ext { 5 | buildToolsVersion = "28.0.3" 6 | minSdkVersion = 17 7 | compileSdkVersion = 28 8 | targetSdkVersion = 28 9 | supportLibVersion = "28.0.0" 10 | 11 | kotlin_version = '1.3.21' 12 | } 13 | repositories { 14 | google() 15 | jcenter() 16 | } 17 | dependencies { 18 | classpath 'com.android.tools.build:gradle:3.3.2' 19 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 20 | // NOTE: Do not place your application dependencies here; they belong 21 | // in the individual module build.gradle files 22 | } 23 | } 24 | 25 | allprojects { 26 | repositories { 27 | mavenLocal() 28 | google() 29 | jcenter() 30 | maven { 31 | // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm 32 | url "$rootDir/../node_modules/react-native/android" 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /android/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true 19 | -------------------------------------------------------------------------------- /android/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yxyhail/MetroExample/0180d2f08ae7849b6838aba379db1a4f69bc5109/android/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | zipStoreBase=GRADLE_USER_HOME 4 | zipStorePath=wrapper/dists 5 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.2-all.zip 6 | -------------------------------------------------------------------------------- /android/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /android/gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /android/keystores/BUCK: -------------------------------------------------------------------------------- 1 | keystore( 2 | name = "debug", 3 | properties = "debug.keystore.properties", 4 | store = "debug.keystore", 5 | visibility = [ 6 | "PUBLIC", 7 | ], 8 | ) 9 | -------------------------------------------------------------------------------- /android/keystores/debug.keystore.properties: -------------------------------------------------------------------------------- 1 | key.store=debug.keystore 2 | key.alias=androiddebugkey 3 | key.store.password=android 4 | key.alias.password=android 5 | -------------------------------------------------------------------------------- /android/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'MetroExample' 2 | 3 | include ':app' 4 | -------------------------------------------------------------------------------- /app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "MetroExample", 3 | "displayName": "MetroExample" 4 | } -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: ['module:metro-react-native-babel-preset'], 3 | }; 4 | -------------------------------------------------------------------------------- /basics.config.js: -------------------------------------------------------------------------------- 1 | const config = require('./metro.config') 2 | 3 | module.exports = { 4 | 5 | serializer: { 6 | createModuleIdFactory: config.createModuleIdFactory, 7 | /* serializer options */ 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /bundle.sh: -------------------------------------------------------------------------------- 1 | #打基础包 2 | #react-native bundle --platform android --dev false --entry-file src/basics/basics.js --bundle-output ./android/app/src/main/assets/basics.android.bundle --assets-dest android/app/src/main/res/ --config basics.config.js 3 | 4 | #打业务1包 5 | #react-native bundle --platform android --dev false --entry-file src/index/index1.js --bundle-output ./android/app/src/main/assets/business1.android.bundle --assets-dest android/app/src/main/res/ --config business.config.js 6 | 7 | #打业务2包 8 | #react-native bundle --platform android --dev false --entry-file src/index/index2.js --bundle-output ./android/app/src/main/assets/business2.android.bundle --assets-dest android/app/src/main/res/ --config business.config.js 9 | 10 | #打业务3包 11 | #react-native bundle --platform android --dev false --entry-file src/index/index3.js --bundle-output ./android/app/src/main/assets/business3.android.bundle --assets-dest android/app/src/main/res/ --config business.config.js 12 | 13 | #打业务4包 14 | #react-native bundle --platform android --dev false --entry-file src/index/index4.js --bundle-output ./android/app/src/main/assets/business4.android.bundle --assets-dest android/app/src/main/res/ --config business.config.js 15 | 16 | react-native bundle --platform android --dev false --entry-file src/basics/basics.js --bundle-output ./android/app/src/main/assets/basics.android.bundle --assets-dest android/app/src/main/res/ --config basics.config.js && react-native bundle --platform android --dev false --entry-file src/index/index1.js --bundle-output ./android/app/src/main/assets/business1.android.bundle --assets-dest android/app/src/main/res/ --config business.config.js && react-native bundle --platform android --dev false --entry-file src/index/index2.js --bundle-output ./android/app/src/main/assets/business2.android.bundle --assets-dest android/app/src/main/res/ --config business.config.js && react-native bundle --platform android --dev false --entry-file src/index/index3.js --bundle-output ./android/app/src/main/assets/business3.android.bundle --assets-dest android/app/src/main/res/ --config business.config.js && react-native bundle --platform android --dev false --entry-file src/index/index4.js --bundle-output ./android/app/src/main/assets/business4.android.bundle --assets-dest android/app/src/main/res/ --config business.config.js -------------------------------------------------------------------------------- /business.config.js: -------------------------------------------------------------------------------- 1 | const config = require('./metro.config') 2 | 3 | module.exports = { 4 | 5 | serializer: { 6 | createModuleIdFactory: config.createModuleIdFactory, 7 | processModuleFilter: config.processModuleFilter 8 | /* serializer options */ 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /imgs/bundle-name-encrypt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yxyhail/MetroExample/0180d2f08ae7849b6838aba379db1a4f69bc5109/imgs/bundle-name-encrypt.png -------------------------------------------------------------------------------- /imgs/bundle-name.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yxyhail/MetroExample/0180d2f08ae7849b6838aba379db1a4f69bc5109/imgs/bundle-name.png -------------------------------------------------------------------------------- /imgs/bundle_help.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yxyhail/MetroExample/0180d2f08ae7849b6838aba379db1a4f69bc5109/imgs/bundle_help.png -------------------------------------------------------------------------------- /imgs/ios-img1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yxyhail/MetroExample/0180d2f08ae7849b6838aba379db1a4f69bc5109/imgs/ios-img1.png -------------------------------------------------------------------------------- /imgs/ios-img2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yxyhail/MetroExample/0180d2f08ae7849b6838aba379db1a4f69bc5109/imgs/ios-img2.png -------------------------------------------------------------------------------- /imgs/ios-img3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yxyhail/MetroExample/0180d2f08ae7849b6838aba379db1a4f69bc5109/imgs/ios-img3.png -------------------------------------------------------------------------------- /imgs/ios-img4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yxyhail/MetroExample/0180d2f08ae7849b6838aba379db1a4f69bc5109/imgs/ios-img4.png -------------------------------------------------------------------------------- /imgs/metro.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yxyhail/MetroExample/0180d2f08ae7849b6838aba379db1a4f69bc5109/imgs/metro.gif -------------------------------------------------------------------------------- /imgs/metro_config.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yxyhail/MetroExample/0180d2f08ae7849b6838aba379db1a4f69bc5109/imgs/metro_config.png -------------------------------------------------------------------------------- /imgs/moduleid-app.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yxyhail/MetroExample/0180d2f08ae7849b6838aba379db1a4f69bc5109/imgs/moduleid-app.png -------------------------------------------------------------------------------- /imgs/moduleid-core.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yxyhail/MetroExample/0180d2f08ae7849b6838aba379db1a4f69bc5109/imgs/moduleid-core.png -------------------------------------------------------------------------------- /imgs/moduleid-thirdlib.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yxyhail/MetroExample/0180d2f08ae7849b6838aba379db1a4f69bc5109/imgs/moduleid-thirdlib.png -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | import './src/index/index1'; 2 | import './src/index/index2'; 3 | import './src/index/index3'; 4 | import './src/index/index4'; -------------------------------------------------------------------------------- /ios/MetroExample-tvOS/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | APPL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | LSRequiresIPhoneOS 24 | 25 | UILaunchStoryboardName 26 | LaunchScreen 27 | UIRequiredDeviceCapabilities 28 | 29 | armv7 30 | 31 | UISupportedInterfaceOrientations 32 | 33 | UIInterfaceOrientationPortrait 34 | UIInterfaceOrientationLandscapeLeft 35 | UIInterfaceOrientationLandscapeRight 36 | 37 | UIViewControllerBasedStatusBarAppearance 38 | 39 | NSLocationWhenInUseUsageDescription 40 | 41 | NSAppTransportSecurity 42 | 43 | 44 | NSExceptionDomains 45 | 46 | localhost 47 | 48 | NSExceptionAllowsInsecureHTTPLoads 49 | 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /ios/MetroExample-tvOSTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /ios/MetroExample.xcodeproj/xcshareddata/xcschemes/MetroExample-tvOS.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 29 | 35 | 36 | 37 | 43 | 49 | 50 | 51 | 52 | 53 | 58 | 59 | 61 | 67 | 68 | 69 | 70 | 71 | 77 | 78 | 79 | 80 | 81 | 82 | 92 | 94 | 100 | 101 | 102 | 103 | 104 | 105 | 111 | 113 | 119 | 120 | 121 | 122 | 124 | 125 | 128 | 129 | 130 | -------------------------------------------------------------------------------- /ios/MetroExample.xcodeproj/xcshareddata/xcschemes/MetroExample.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 29 | 35 | 36 | 37 | 43 | 49 | 50 | 51 | 52 | 53 | 58 | 59 | 61 | 67 | 68 | 69 | 70 | 71 | 77 | 78 | 79 | 80 | 81 | 82 | 92 | 94 | 100 | 101 | 102 | 103 | 104 | 105 | 111 | 113 | 119 | 120 | 121 | 122 | 124 | 125 | 128 | 129 | 130 | -------------------------------------------------------------------------------- /ios/MetroExample/AppDelegate.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | #import 9 | #import 10 | 11 | @interface AppDelegate : UIResponder 12 | 13 | @property (nonatomic, strong) UIWindow *window; 14 | 15 | @end 16 | -------------------------------------------------------------------------------- /ios/MetroExample/AppDelegate.m: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | #import "AppDelegate.h" 9 | 10 | #import 11 | #import 12 | #import 13 | 14 | @implementation AppDelegate 15 | 16 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 17 | { 18 | RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions]; 19 | RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge 20 | moduleName:@"MetroExample" 21 | initialProperties:nil]; 22 | 23 | rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1]; 24 | 25 | self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; 26 | UIViewController *rootViewController = [UIViewController new]; 27 | rootViewController.view = rootView; 28 | self.window.rootViewController = rootViewController; 29 | [self.window makeKeyAndVisible]; 30 | return YES; 31 | } 32 | 33 | - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge 34 | { 35 | #if DEBUG 36 | return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil]; 37 | #else 38 | return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"]; 39 | #endif 40 | } 41 | 42 | @end 43 | -------------------------------------------------------------------------------- /ios/MetroExample/Base.lproj/LaunchScreen.xib: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 21 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /ios/MetroExample/Images.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "size" : "29x29", 6 | "scale" : "2x" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "size" : "29x29", 11 | "scale" : "3x" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "size" : "40x40", 16 | "scale" : "2x" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "size" : "40x40", 21 | "scale" : "3x" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "size" : "60x60", 26 | "scale" : "2x" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "size" : "60x60", 31 | "scale" : "3x" 32 | } 33 | ], 34 | "info" : { 35 | "version" : 1, 36 | "author" : "xcode" 37 | } 38 | } -------------------------------------------------------------------------------- /ios/MetroExample/Images.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /ios/MetroExample/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleDisplayName 8 | MetroExample 9 | CFBundleExecutable 10 | $(EXECUTABLE_NAME) 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | $(PRODUCT_NAME) 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | 1.0 21 | CFBundleSignature 22 | ???? 23 | CFBundleVersion 24 | 1 25 | LSRequiresIPhoneOS 26 | 27 | NSLocationWhenInUseUsageDescription 28 | 29 | UILaunchStoryboardName 30 | LaunchScreen 31 | UIRequiredDeviceCapabilities 32 | 33 | armv7 34 | 35 | UISupportedInterfaceOrientations 36 | 37 | UIInterfaceOrientationPortrait 38 | UIInterfaceOrientationLandscapeLeft 39 | UIInterfaceOrientationLandscapeRight 40 | 41 | UIViewControllerBasedStatusBarAppearance 42 | 43 | NSLocationWhenInUseUsageDescription 44 | 45 | NSAppTransportSecurity 46 | 47 | 48 | NSAllowsArbitraryLoads 49 | 50 | NSExceptionDomains 51 | 52 | localhost 53 | 54 | NSExceptionAllowsInsecureHTTPLoads 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /ios/MetroExample/main.m: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | #import 9 | 10 | #import "AppDelegate.h" 11 | 12 | int main(int argc, char * argv[]) { 13 | @autoreleasepool { 14 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /ios/MetroExampleTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /ios/MetroExampleTests/MetroExampleTests.m: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | #import 9 | #import 10 | 11 | #import 12 | #import 13 | 14 | #define TIMEOUT_SECONDS 600 15 | #define TEXT_TO_LOOK_FOR @"Welcome to React Native!" 16 | 17 | @interface MetroExampleTests : XCTestCase 18 | 19 | @end 20 | 21 | @implementation MetroExampleTests 22 | 23 | - (BOOL)findSubviewInView:(UIView *)view matching:(BOOL(^)(UIView *view))test 24 | { 25 | if (test(view)) { 26 | return YES; 27 | } 28 | for (UIView *subview in [view subviews]) { 29 | if ([self findSubviewInView:subview matching:test]) { 30 | return YES; 31 | } 32 | } 33 | return NO; 34 | } 35 | 36 | - (void)testRendersWelcomeScreen 37 | { 38 | UIViewController *vc = [[[RCTSharedApplication() delegate] window] rootViewController]; 39 | NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS]; 40 | BOOL foundElement = NO; 41 | 42 | __block NSString *redboxError = nil; 43 | RCTSetLogFunction(^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) { 44 | if (level >= RCTLogLevelError) { 45 | redboxError = message; 46 | } 47 | }); 48 | 49 | while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) { 50 | [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; 51 | [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; 52 | 53 | foundElement = [self findSubviewInView:vc.view matching:^BOOL(UIView *view) { 54 | if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) { 55 | return YES; 56 | } 57 | return NO; 58 | }]; 59 | } 60 | 61 | RCTSetLogFunction(RCTDefaultLogFunction); 62 | 63 | XCTAssertNil(redboxError, @"RedBox error: %@", redboxError); 64 | XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS); 65 | } 66 | 67 | 68 | @end 69 | -------------------------------------------------------------------------------- /metro.config.js: -------------------------------------------------------------------------------- 1 | const pathSep = require('path').sep; 2 | const md5 = require('js-md5'); 3 | //是否加密 4 | const isEncrypt = true; 5 | 6 | function createModuleIdFactory() { 7 | //获取命令行执行的目录,__dirname是nodejs提供的变量 8 | const projectRootPath = __dirname; 9 | return (path) => { 10 | console.log(''); 11 | console.log(path); 12 | let name = ''; 13 | // 如果需要去除react-native/Libraries路径去除可以放开下面代码 14 | // if (path.indexOf('node_modules' + pathSep + 'react-native' + pathSep + 'Libraries' + pathSep) > 0) { 15 | // //这里是react native 自带的库,因其一般不会改变路径,所以可直接截取最后的文件名称 16 | // name = path.substr(path.lastIndexOf(pathSep) + 1); 17 | // console.log('react libraries:' + name); 18 | // } 19 | if (path.indexOf(projectRootPath) == 0) { 20 | /* 21 | 这里是react native 自带库以外的其他库,因是绝对路径,带有设备信息, 22 | 为了避免重复名称,可以保留node_modules直至结尾 23 | 如/{User}/{username}/{userdir}/node_modules/xxx.js 需要将设备信息截掉 24 | */ 25 | name = path.substr(projectRootPath.length + 1); 26 | console.log('root libraries:' + name); 27 | } 28 | //js png字符串 文件的后缀名可以去掉 29 | // name = name.replace('.js', ''); 30 | // name = name.replace('.png', ''); 31 | console.log('replace name:' + name); 32 | //最后在将斜杠替换为空串或下划线 33 | let regExp = pathSep == '\\' ? new RegExp('\\\\', "gm") : new RegExp(pathSep, "gm"); 34 | name = name.replace(regExp, '_'); 35 | console.log('regExp name:' + name); 36 | //名称加密 37 | if (isEncrypt) { 38 | name = md5(name); 39 | console.log('encryptName:' + name); 40 | } 41 | 42 | return name; 43 | }; 44 | } 45 | 46 | function processModuleFilter(module) { 47 | // console.log(module) 48 | //过滤掉path为__prelude__的一些模块(基础包内已有) 49 | if (module['path'].indexOf('__prelude__') >= 0) { 50 | return false; 51 | } 52 | //过滤掉node_modules内的模块(基础包内已有) 53 | if (module['path'].indexOf(pathSep + 'node_modules' + pathSep) > 0) { 54 | /* 55 | 但输出类型为js/script/virtual的模块不能过滤,一般此类型的文件为核心文件, 56 | 如InitializeCore.js。每次加载bundle文件时都需要用到。 57 | */ 58 | if ('js' + pathSep + 'script' + pathSep + 'virtual' == module['output'][0]['type']) { 59 | return true; 60 | } 61 | return false; 62 | } 63 | console.log(module.path) 64 | //其他就是应用代码 65 | return true; 66 | } 67 | 68 | 69 | module.exports = { 70 | createModuleIdFactory, 71 | processModuleFilter 72 | } 73 | 74 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "MetroExample", 3 | "version": "0.0.1", 4 | "private": true, 5 | "scripts": { 6 | "start": "node node_modules/react-native/local-cli/cli.js start", 7 | "test": "jest" 8 | }, 9 | "dependencies": { 10 | "js-md5": "^0.7.3", 11 | "react": "16.8.3", 12 | "react-native": "0.59.3" 13 | }, 14 | "devDependencies": { 15 | "@babel/core": "^7.4.3", 16 | "@babel/runtime": "^7.4.3", 17 | "babel-jest": "^24.7.1", 18 | "jest": "^24.7.1", 19 | "metro-react-native-babel-preset": "^0.53.1", 20 | "react-test-renderer": "16.8.3" 21 | }, 22 | "jest": { 23 | "preset": "react-native" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/basics/basics.js: -------------------------------------------------------------------------------- 1 | import 'react'; 2 | import 'react-native'; 3 | 4 | import React, { Component } from "react"; 5 | 6 | import { Text } from "react-native"; 7 | 8 | 9 | var _ = require('lodash'); 10 | Text.render = _.wrap(Text.render, function (func, ...args) { 11 | let originText = func.apply(this, args) 12 | return React.cloneElement(originText, { allowFontScaling: false }) 13 | }) 14 | -------------------------------------------------------------------------------- /src/business/Business1.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Sample React Native App 3 | * https://github.com/facebook/react-native 4 | * 5 | * @format 6 | * @flow 7 | */ 8 | 9 | import React, { Component } from 'react'; 10 | import { StyleSheet, Text, View } from 'react-native'; 11 | 12 | const instructions = 'Business1'; 13 | 14 | export default class App extends Component { 15 | render() { 16 | return ( 17 | 18 | 欢迎来到{instructions}!Load Runtime 19 | To get started, edit {instructions}.js 20 | {instructions} 21 | 22 | ); 23 | } 24 | } 25 | 26 | const styles = StyleSheet.create({ 27 | container: { 28 | flex: 1, 29 | justifyContent: 'center', 30 | alignItems: 'center', 31 | backgroundColor: '#F5FCFF', 32 | }, 33 | welcome: { 34 | fontSize: 20, 35 | textAlign: 'center', 36 | margin: 10, 37 | }, 38 | instructions: { 39 | textAlign: 'center', 40 | color: '#333333', 41 | marginBottom: 5, 42 | }, 43 | }); 44 | -------------------------------------------------------------------------------- /src/business/Business2.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Sample React Native App 3 | * https://github.com/facebook/react-native 4 | * 5 | * @format 6 | * @flow 7 | */ 8 | 9 | import React, { Component } from 'react'; 10 | import { StyleSheet, Text, View } from 'react-native'; 11 | 12 | const instructions = 'Business2'; 13 | 14 | export default class App extends Component { 15 | render() { 16 | return ( 17 | 18 | 欢迎来到{instructions}!Load Runtime 19 | To get started, edit {instructions}.js 20 | {instructions} 21 | 22 | ); 23 | } 24 | } 25 | 26 | const styles = StyleSheet.create({ 27 | container: { 28 | flex: 1, 29 | justifyContent: 'center', 30 | alignItems: 'center', 31 | backgroundColor: '#F5FCFF', 32 | }, 33 | welcome: { 34 | fontSize: 20, 35 | textAlign: 'center', 36 | margin: 10, 37 | }, 38 | instructions: { 39 | textAlign: 'center', 40 | color: '#333333', 41 | marginBottom: 5, 42 | }, 43 | }); 44 | -------------------------------------------------------------------------------- /src/business/Business3.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Sample React Native App 3 | * https://github.com/facebook/react-native 4 | * 5 | * @format 6 | * @flow 7 | */ 8 | 9 | import React, { Component } from 'react'; 10 | import { StyleSheet, Text, View } from 'react-native'; 11 | 12 | const instructions = 'Business3'; 13 | 14 | export default class App extends Component { 15 | render() { 16 | return ( 17 | 18 | 欢迎来到{instructions}!Load Runtime 19 | To get started, edit {instructions}.js 20 | {instructions} 21 | 22 | ); 23 | } 24 | } 25 | 26 | const styles = StyleSheet.create({ 27 | container: { 28 | flex: 1, 29 | justifyContent: 'center', 30 | alignItems: 'center', 31 | backgroundColor: '#F5FCFF', 32 | }, 33 | welcome: { 34 | fontSize: 20, 35 | textAlign: 'center', 36 | margin: 10, 37 | }, 38 | instructions: { 39 | textAlign: 'center', 40 | color: '#333333', 41 | marginBottom: 5, 42 | }, 43 | }); 44 | -------------------------------------------------------------------------------- /src/business/Business4.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Sample React Native App 3 | * https://github.com/facebook/react-native 4 | * 5 | * @format 6 | * @flow 7 | */ 8 | 9 | import React, { Component } from 'react'; 10 | import { StyleSheet, Text, View } from 'react-native'; 11 | 12 | const instructions = 'Business4'; 13 | 14 | export default class App extends Component { 15 | render() { 16 | return ( 17 | 18 | 欢迎来到{instructions}!Load Runtime 19 | To get started, edit {instructions}.js 20 | {instructions} 21 | 22 | ); 23 | } 24 | } 25 | 26 | const styles = StyleSheet.create({ 27 | container: { 28 | flex: 1, 29 | justifyContent: 'center', 30 | alignItems: 'center', 31 | backgroundColor: '#F5FCFF', 32 | }, 33 | welcome: { 34 | fontSize: 20, 35 | textAlign: 'center', 36 | margin: 10, 37 | }, 38 | instructions: { 39 | textAlign: 'center', 40 | color: '#333333', 41 | marginBottom: 5, 42 | }, 43 | }); 44 | -------------------------------------------------------------------------------- /src/index/index1.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @format 3 | */ 4 | 5 | import { AppRegistry } from 'react-native'; 6 | import App from '../business/Business1'; 7 | 8 | AppRegistry.registerComponent('App1', () => App); 9 | 10 | -------------------------------------------------------------------------------- /src/index/index2.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @format 3 | */ 4 | 5 | import { AppRegistry } from 'react-native'; 6 | import App from '../business/Business2'; 7 | 8 | AppRegistry.registerComponent('App2', () => App); 9 | 10 | -------------------------------------------------------------------------------- /src/index/index3.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @format 3 | */ 4 | 5 | import { AppRegistry } from 'react-native'; 6 | import App from '../business/Business3'; 7 | 8 | AppRegistry.registerComponent('App3', () => App); 9 | 10 | -------------------------------------------------------------------------------- /src/index/index4.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @format 3 | */ 4 | 5 | import { AppRegistry } from 'react-native'; 6 | import App from '../business/Business4'; 7 | 8 | AppRegistry.registerComponent('App4', () => App); 9 | 10 | --------------------------------------------------------------------------------