react.gradle 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. import org.apache.tools.ant.taskdefs.condition.Os
  8. def config = project.hasProperty("react") ? project.react : [:];
  9. def detectEntryFile(config) {
  10. if (System.getenv('ENTRY_FILE')) {
  11. return System.getenv('ENTRY_FILE')
  12. } else if (config.entryFile) {
  13. return config.entryFile
  14. } else if ((new File("${projectDir}/../../index.android.js")).exists()) {
  15. return "index.android.js"
  16. }
  17. return "index.js";
  18. }
  19. /**
  20. * Detects CLI location in a similar fashion to the React Native CLI
  21. */
  22. def detectCliPath(config) {
  23. if (config.cliPath) {
  24. return config.cliPath
  25. }
  26. def cliPath = ["node", "-e", "console.log(require('react-native/cli').bin);"].execute([], projectDir).text.trim()
  27. if (cliPath) {
  28. return cliPath
  29. } else if (new File("${projectDir}/../../node_modules/react-native/cli.js").exists()) {
  30. return "${projectDir}/../../node_modules/react-native/cli.js"
  31. } else {
  32. throw new Exception("Couldn't determine CLI location. " +
  33. "Please set `project.ext.react.cliPath` to the path of the react-native cli.js");
  34. }
  35. }
  36. def composeSourceMapsPath = config.composeSourceMapsPath ?: "node_modules/react-native/scripts/compose-source-maps.js"
  37. def bundleAssetName = config.bundleAssetName ?: "index.android.bundle"
  38. def entryFile = detectEntryFile(config)
  39. def bundleCommand = config.bundleCommand ?: "bundle"
  40. def reactRoot = file(config.root ?: "../../")
  41. def inputExcludes = config.inputExcludes ?: ["android/**", "ios/**"]
  42. def bundleConfig = config.bundleConfig ? "${reactRoot}/${config.bundleConfig}" : null ;
  43. def enableVmCleanup = config.enableVmCleanup == null ? true : config.enableVmCleanup
  44. def hermesCommand = config.hermesCommand ?: "../../node_modules/hermes-engine/%OS-BIN%/hermesc"
  45. def reactNativeDevServerPort() {
  46. def value = project.getProperties().get("reactNativeDevServerPort")
  47. return value != null ? value : "8081"
  48. }
  49. def reactNativeInspectorProxyPort() {
  50. def value = project.getProperties().get("reactNativeInspectorProxyPort")
  51. return value != null ? value : reactNativeDevServerPort()
  52. }
  53. def getHermesOSBin() {
  54. if (Os.isFamily(Os.FAMILY_WINDOWS)) return "win64-bin";
  55. if (Os.isFamily(Os.FAMILY_MAC)) return "osx-bin";
  56. if (Os.isOs(null, "linux", "amd64", null)) return "linux64-bin";
  57. throw new Exception("OS not recognized. Please set project.ext.react.hermesCommand " +
  58. "to the path of a working Hermes compiler.");
  59. }
  60. // Make sure not to inspect the Hermes config unless we need it,
  61. // to avoid breaking any JSC-only setups.
  62. def getHermesCommand = {
  63. // If the project specifies a Hermes command, don't second guess it.
  64. if (!hermesCommand.contains("%OS-BIN%")) {
  65. return hermesCommand
  66. }
  67. // Execution on Windows fails with / as separator
  68. return hermesCommand
  69. .replaceAll("%OS-BIN%", getHermesOSBin())
  70. .replace('/' as char, File.separatorChar);
  71. }
  72. // Set enableHermesForVariant to a function to configure per variant,
  73. // or set `enableHermes` to True/False to set all of them
  74. def enableHermesForVariant = config.enableHermesForVariant ?: {
  75. def variant -> config.enableHermes ?: false
  76. }
  77. android {
  78. buildTypes.all {
  79. resValue "integer", "react_native_dev_server_port", reactNativeDevServerPort()
  80. resValue "integer", "react_native_inspector_proxy_port", reactNativeInspectorProxyPort()
  81. }
  82. }
  83. afterEvaluate {
  84. def isAndroidLibrary = plugins.hasPlugin("com.android.library")
  85. def variants = isAndroidLibrary ? android.libraryVariants : android.applicationVariants
  86. variants.all { def variant ->
  87. // Create variant and target names
  88. def targetName = variant.name.capitalize()
  89. def targetPath = variant.dirName
  90. // React js bundle directories
  91. def jsBundleDir = file("$buildDir/generated/assets/react/${targetPath}")
  92. def resourcesDir = file("$buildDir/generated/res/react/${targetPath}")
  93. def jsBundleFile = file("$jsBundleDir/$bundleAssetName")
  94. def jsSourceMapsDir = file("$buildDir/generated/sourcemaps/react/${targetPath}")
  95. def jsIntermediateSourceMapsDir = file("$buildDir/intermediates/sourcemaps/react/${targetPath}")
  96. def jsPackagerSourceMapFile = file("$jsIntermediateSourceMapsDir/${bundleAssetName}.packager.map")
  97. def jsCompilerSourceMapFile = file("$jsIntermediateSourceMapsDir/${bundleAssetName}.compiler.map")
  98. def jsOutputSourceMapFile = file("$jsSourceMapsDir/${bundleAssetName}.map")
  99. // Additional node and packager commandline arguments
  100. def nodeExecutableAndArgs = config.nodeExecutableAndArgs ?: ["node"]
  101. def cliPath = detectCliPath(config)
  102. def execCommand = []
  103. if (Os.isFamily(Os.FAMILY_WINDOWS)) {
  104. execCommand.addAll(["cmd", "/c", *nodeExecutableAndArgs, cliPath])
  105. } else {
  106. execCommand.addAll([*nodeExecutableAndArgs, cliPath])
  107. }
  108. def enableHermes = enableHermesForVariant(variant)
  109. def currentBundleTask = tasks.create(
  110. name: "bundle${targetName}JsAndAssets",
  111. type: Exec) {
  112. group = "react"
  113. description = "bundle JS and assets for ${targetName}."
  114. // Create dirs if they are not there (e.g. the "clean" task just ran)
  115. doFirst {
  116. jsBundleDir.deleteDir()
  117. jsBundleDir.mkdirs()
  118. resourcesDir.deleteDir()
  119. resourcesDir.mkdirs()
  120. jsIntermediateSourceMapsDir.deleteDir()
  121. jsIntermediateSourceMapsDir.mkdirs()
  122. jsSourceMapsDir.deleteDir()
  123. jsSourceMapsDir.mkdirs()
  124. }
  125. // Set up inputs and outputs so gradle can cache the result
  126. inputs.files fileTree(dir: reactRoot, excludes: inputExcludes)
  127. outputs.dir(jsBundleDir)
  128. outputs.dir(resourcesDir)
  129. // Set up the call to the react-native cli
  130. workingDir(reactRoot)
  131. // Set up dev mode
  132. def devEnabled = !(config."devDisabledIn${targetName}"
  133. || targetName.toLowerCase().contains("release"))
  134. def extraArgs = config.extraPackagerArgs ?: [];
  135. if (bundleConfig) {
  136. extraArgs = extraArgs.clone()
  137. extraArgs.add("--config");
  138. extraArgs.add(bundleConfig);
  139. }
  140. commandLine(*execCommand, bundleCommand, "--platform", "android", "--dev", "${devEnabled}",
  141. "--reset-cache", "--entry-file", entryFile, "--bundle-output", jsBundleFile, "--assets-dest", resourcesDir,
  142. "--sourcemap-output", enableHermes ? jsPackagerSourceMapFile : jsOutputSourceMapFile, *extraArgs)
  143. if (enableHermes) {
  144. doLast {
  145. def hermesFlags;
  146. def hbcTempFile = file("${jsBundleFile}.hbc")
  147. exec {
  148. if (targetName.toLowerCase().contains("release")) {
  149. // Can't use ?: since that will also substitute valid empty lists
  150. hermesFlags = config.hermesFlagsRelease
  151. if (hermesFlags == null) hermesFlags = ["-O", "-output-source-map"]
  152. } else {
  153. hermesFlags = config.hermesFlagsDebug
  154. if (hermesFlags == null) hermesFlags = []
  155. }
  156. if (Os.isFamily(Os.FAMILY_WINDOWS)) {
  157. commandLine("cmd", "/c", getHermesCommand(), "-emit-binary", "-out", hbcTempFile, jsBundleFile, *hermesFlags)
  158. } else {
  159. commandLine(getHermesCommand(), "-emit-binary", "-out", hbcTempFile, jsBundleFile, *hermesFlags)
  160. }
  161. }
  162. ant.move(
  163. file: hbcTempFile,
  164. toFile: jsBundleFile
  165. );
  166. if (hermesFlags.contains("-output-source-map")) {
  167. ant.move(
  168. // Hermes will generate a source map with this exact name
  169. file: "${jsBundleFile}.hbc.map",
  170. tofile: jsCompilerSourceMapFile
  171. );
  172. exec {
  173. // TODO: set task dependencies for caching
  174. // Set up the call to the compose-source-maps script
  175. workingDir(reactRoot)
  176. if (Os.isFamily(Os.FAMILY_WINDOWS)) {
  177. commandLine("cmd", "/c", *nodeExecutableAndArgs, composeSourceMapsPath, jsPackagerSourceMapFile, jsCompilerSourceMapFile, "-o", jsOutputSourceMapFile)
  178. } else {
  179. commandLine(*nodeExecutableAndArgs, composeSourceMapsPath, jsPackagerSourceMapFile, jsCompilerSourceMapFile, "-o", jsOutputSourceMapFile)
  180. }
  181. }
  182. }
  183. }
  184. }
  185. enabled config."bundleIn${targetName}" != null
  186. ? config."bundleIn${targetName}"
  187. : config."bundleIn${variant.buildType.name.capitalize()}" != null
  188. ? config."bundleIn${variant.buildType.name.capitalize()}"
  189. : targetName.toLowerCase().contains("release")
  190. }
  191. // Expose a minimal interface on the application variant and the task itself:
  192. variant.ext.bundleJsAndAssets = currentBundleTask
  193. currentBundleTask.ext.generatedResFolders = files(resourcesDir).builtBy(currentBundleTask)
  194. currentBundleTask.ext.generatedAssetsFolders = files(jsBundleDir).builtBy(currentBundleTask)
  195. // registerGeneratedResFolders for Android plugin 3.x
  196. if (variant.respondsTo("registerGeneratedResFolders")) {
  197. variant.registerGeneratedResFolders(currentBundleTask.generatedResFolders)
  198. } else {
  199. variant.registerResGeneratingTask(currentBundleTask)
  200. }
  201. variant.mergeResourcesProvider.get().dependsOn(currentBundleTask)
  202. // packageApplication for Android plugin 3.x
  203. def packageTask = variant.hasProperty("packageApplication")
  204. ? variant.packageApplicationProvider.get()
  205. : tasks.findByName("package${targetName}")
  206. if (variant.hasProperty("packageLibrary")) {
  207. packageTask = variant.packageLibrary
  208. }
  209. // pre bundle build task for Android plugin 3.2+
  210. def buildPreBundleTask = tasks.findByName("build${targetName}PreBundle")
  211. def resourcesDirConfigValue = config."resourcesDir${targetName}"
  212. if (resourcesDirConfigValue) {
  213. def currentCopyResTask = tasks.create(
  214. name: "copy${targetName}BundledResources",
  215. type: Copy) {
  216. group = "react"
  217. description = "copy bundled resources into custom location for ${targetName}."
  218. from(resourcesDir)
  219. into(file(resourcesDirConfigValue))
  220. dependsOn(currentBundleTask)
  221. enabled(currentBundleTask.enabled)
  222. }
  223. packageTask.dependsOn(currentCopyResTask)
  224. if (buildPreBundleTask != null) {
  225. buildPreBundleTask.dependsOn(currentCopyResTask)
  226. }
  227. }
  228. def currentAssetsCopyTask = tasks.create(
  229. name: "copy${targetName}BundledJs",
  230. type: Copy) {
  231. group = "react"
  232. description = "copy bundled JS into ${targetName}."
  233. if (config."jsBundleDir${targetName}") {
  234. from(jsBundleDir)
  235. into(file(config."jsBundleDir${targetName}"))
  236. } else {
  237. into ("$buildDir/intermediates")
  238. into ("assets/${targetPath}") {
  239. from(jsBundleDir)
  240. }
  241. // Workaround for Android Gradle Plugin 3.2+ new asset directory
  242. into ("merged_assets/${variant.name}/merge${targetName}Assets/out") {
  243. from(jsBundleDir)
  244. }
  245. // Workaround for Android Gradle Plugin 3.4+ new asset directory
  246. into ("merged_assets/${variant.name}/out") {
  247. from(jsBundleDir)
  248. }
  249. }
  250. // mergeAssets must run first, as it clears the intermediates directory
  251. dependsOn(variant.mergeAssetsProvider.get())
  252. enabled(currentBundleTask.enabled)
  253. }
  254. // mergeResources task runs before the bundle file is copied to the intermediate asset directory from Android plugin 4.1+.
  255. // This ensures to copy the bundle file before mergeResources task starts
  256. def mergeResourcesTask = tasks.findByName("merge${targetName}Resources")
  257. mergeResourcesTask.dependsOn(currentAssetsCopyTask)
  258. packageTask.dependsOn(currentAssetsCopyTask)
  259. if (buildPreBundleTask != null) {
  260. buildPreBundleTask.dependsOn(currentAssetsCopyTask)
  261. }
  262. // Delete the VM related libraries that this build doesn't need.
  263. // The application can manage this manually by setting 'enableVmCleanup: false'
  264. //
  265. // This should really be done by packaging all Hermes releated libs into
  266. // two separate HermesDebug and HermesRelease AARs, but until then we'll
  267. // kludge it by deleting the .so files out of the /transforms/ directory.
  268. def isRelease = targetName.toLowerCase().contains("release")
  269. def libDir = "$buildDir/intermediates/transforms/"
  270. def vmSelectionAction = {
  271. fileTree(libDir).matching {
  272. if (enableHermes) {
  273. // For Hermes, delete all the libjsc* files
  274. include "**/libjsc*.so"
  275. if (isRelease) {
  276. // Reduce size by deleting the debugger/inspector
  277. include '**/libhermes-inspector.so'
  278. include '**/libhermes-executor-debug.so'
  279. } else {
  280. // Release libs take precedence and must be removed
  281. // to allow debugging
  282. include '**/libhermes-executor-release.so'
  283. }
  284. } else {
  285. // For JSC, delete all the libhermes* files
  286. include "**/libhermes*.so"
  287. }
  288. }.visit { details ->
  289. def targetVariant = ".*/transforms/[^/]*/${targetPath}/.*"
  290. def path = details.file.getAbsolutePath().replace(File.separatorChar, '/' as char)
  291. if (path.matches(targetVariant) && details.file.isFile()) {
  292. details.file.delete()
  293. }
  294. }
  295. }
  296. if (enableVmCleanup) {
  297. def task = tasks.findByName("package${targetName}")
  298. task.doFirst(vmSelectionAction)
  299. }
  300. }
  301. }