build.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. // @ts-check
  2. /*
  3. Produces production builds and stitches together d.ts files.
  4. To specify the package to build, simply pass its name and the desired build
  5. formats to output (defaults to `buildOptions.formats` specified in that package,
  6. or "esm,cjs"):
  7. ```
  8. # name supports fuzzy match. will build all packages with name containing "dom":
  9. nr build dom
  10. # specify the format to output
  11. nr build core --formats cjs
  12. ```
  13. */
  14. import fs from 'node:fs/promises'
  15. import { existsSync } from 'node:fs'
  16. import path from 'node:path'
  17. import minimist from 'minimist'
  18. import { gzipSync, brotliCompressSync } from 'node:zlib'
  19. import pico from 'picocolors'
  20. import { execa, execaSync } from 'execa'
  21. import { cpus } from 'node:os'
  22. import { createRequire } from 'node:module'
  23. import { targets as allTargets, fuzzyMatchTarget } from './utils.js'
  24. import { scanEnums } from './const-enum.js'
  25. import prettyBytes from 'pretty-bytes'
  26. const require = createRequire(import.meta.url)
  27. const args = minimist(process.argv.slice(2))
  28. const targets = args._
  29. const formats = args.formats || args.f
  30. const devOnly = args.devOnly || args.d
  31. const prodOnly = !devOnly && (args.prodOnly || args.p)
  32. const buildTypes = args.withTypes || args.t
  33. const sourceMap = args.sourcemap || args.s
  34. const isRelease = args.release
  35. const buildAllMatching = args.all || args.a
  36. const writeSize = args.size
  37. const commit = execaSync('git', ['rev-parse', '--short=7', 'HEAD']).stdout
  38. const sizeDir = path.resolve('temp/size')
  39. run()
  40. async function run() {
  41. if (writeSize) await fs.mkdir(sizeDir, { recursive: true })
  42. const removeCache = scanEnums()
  43. try {
  44. const resolvedTargets = targets.length
  45. ? fuzzyMatchTarget(targets, buildAllMatching)
  46. : allTargets
  47. await buildAll(resolvedTargets)
  48. await checkAllSizes(resolvedTargets)
  49. if (buildTypes) {
  50. await execa(
  51. 'pnpm',
  52. [
  53. 'run',
  54. 'build-dts',
  55. ...(targets.length
  56. ? ['--environment', `TARGETS:${resolvedTargets.join(',')}`]
  57. : [])
  58. ],
  59. {
  60. stdio: 'inherit'
  61. }
  62. )
  63. }
  64. } finally {
  65. removeCache()
  66. }
  67. }
  68. /**
  69. * Builds all the targets in parallel.
  70. * @param {Array<string>} targets - An array of targets to build.
  71. * @returns {Promise<void>} - A promise representing the build process.
  72. */
  73. async function buildAll(targets) {
  74. await runParallel(cpus().length, targets, build)
  75. }
  76. /**
  77. * Runs iterator function in parallel.
  78. * @template T - The type of items in the data source
  79. * @param {number} maxConcurrency - The maximum concurrency.
  80. * @param {Array<T>} source - The data source
  81. * @param {(item: T) => Promise<void>} iteratorFn - The iteratorFn
  82. * @returns {Promise<void[]>} - A Promise array containing all iteration results.
  83. */
  84. async function runParallel(maxConcurrency, source, iteratorFn) {
  85. /**@type {Promise<void>[]} */
  86. const ret = []
  87. /**@type {Promise<void>[]} */
  88. const executing = []
  89. for (const item of source) {
  90. const p = Promise.resolve().then(() => iteratorFn(item))
  91. ret.push(p)
  92. if (maxConcurrency <= source.length) {
  93. const e = p.then(() => executing.splice(executing.indexOf(e), 1))
  94. executing.push(e)
  95. if (executing.length >= maxConcurrency) {
  96. await Promise.race(executing)
  97. }
  98. }
  99. }
  100. return Promise.all(ret)
  101. }
  102. /**
  103. * Builds the target.
  104. * @param {string} target - The target to build.
  105. * @returns {Promise<void>} - A promise representing the build process.
  106. */
  107. async function build(target) {
  108. const pkgDir = path.resolve(`packages/${target}`)
  109. const pkg = require(`${pkgDir}/package.json`)
  110. // if this is a full build (no specific targets), ignore private packages
  111. if ((isRelease || !targets.length) && pkg.private) {
  112. return
  113. }
  114. // if building a specific format, do not remove dist.
  115. if (!formats && existsSync(`${pkgDir}/dist`)) {
  116. await fs.rm(`${pkgDir}/dist`, { recursive: true })
  117. }
  118. const env =
  119. (pkg.buildOptions && pkg.buildOptions.env) ||
  120. (devOnly ? 'development' : 'production')
  121. await execa(
  122. 'rollup',
  123. [
  124. '-c',
  125. '--environment',
  126. [
  127. `COMMIT:${commit}`,
  128. `NODE_ENV:${env}`,
  129. `TARGET:${target}`,
  130. formats ? `FORMATS:${formats}` : ``,
  131. prodOnly ? `PROD_ONLY:true` : ``,
  132. sourceMap ? `SOURCE_MAP:true` : ``
  133. ]
  134. .filter(Boolean)
  135. .join(',')
  136. ],
  137. { stdio: 'inherit' }
  138. )
  139. }
  140. /**
  141. * Checks the sizes of all targets.
  142. * @param {string[]} targets - The targets to check sizes for.
  143. * @returns {Promise<void>}
  144. */
  145. async function checkAllSizes(targets) {
  146. if (devOnly || (formats && !formats.includes('global'))) {
  147. return
  148. }
  149. console.log()
  150. for (const target of targets) {
  151. await checkSize(target)
  152. }
  153. console.log()
  154. }
  155. /**
  156. * Checks the size of a target.
  157. * @param {string} target - The target to check the size for.
  158. * @returns {Promise<void>}
  159. */
  160. async function checkSize(target) {
  161. const pkgDir = path.resolve(`packages/${target}`)
  162. await checkFileSize(`${pkgDir}/dist/${target}.global.prod.js`)
  163. if (!formats || formats.includes('global-runtime')) {
  164. await checkFileSize(`${pkgDir}/dist/${target}.runtime.global.prod.js`)
  165. }
  166. }
  167. /**
  168. * Checks the file size.
  169. * @param {string} filePath - The path of the file to check the size for.
  170. * @returns {Promise<void>}
  171. */
  172. async function checkFileSize(filePath) {
  173. if (!existsSync(filePath)) {
  174. return
  175. }
  176. const file = await fs.readFile(filePath)
  177. const fileName = path.basename(filePath)
  178. const gzipped = gzipSync(file)
  179. const brotli = brotliCompressSync(file)
  180. console.log(
  181. `${pico.gray(pico.bold(fileName))} min:${prettyBytes(
  182. file.length
  183. )} / gzip:${prettyBytes(gzipped.length)} / brotli:${prettyBytes(
  184. brotli.length
  185. )}`
  186. )
  187. if (writeSize)
  188. await fs.writeFile(
  189. path.resolve(sizeDir, `${fileName}.json`),
  190. JSON.stringify({
  191. file: fileName,
  192. size: file.length,
  193. gzip: gzipped.length,
  194. brotli: brotli.length
  195. }),
  196. 'utf-8'
  197. )
  198. }