build.js 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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, readFileSync, rmSync } from 'node:fs'
  16. import path from 'node:path'
  17. import minimist from 'minimist'
  18. import { gzipSync, brotliCompressSync } from 'node:zlib'
  19. import chalk from 'chalk'
  20. import execa 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. const require = createRequire(import.meta.url)
  26. const args = minimist(process.argv.slice(2))
  27. const targets = args._
  28. const formats = args.formats || args.f
  29. const devOnly = args.devOnly || args.d
  30. const prodOnly = !devOnly && (args.prodOnly || args.p)
  31. const buildTypes = args.withTypes || args.t
  32. const sourceMap = args.sourcemap || args.s
  33. const isRelease = args.release
  34. const buildAllMatching = args.all || args.a
  35. const commit = execa.sync('git', ['rev-parse', 'HEAD']).stdout.slice(0, 7)
  36. run()
  37. async function run() {
  38. const removeCache = scanEnums()
  39. try {
  40. const resolvedTargets = targets.length
  41. ? fuzzyMatchTarget(targets, buildAllMatching)
  42. : allTargets
  43. await buildAll(resolvedTargets)
  44. checkAllSizes(resolvedTargets)
  45. if (buildTypes) {
  46. await execa(
  47. 'pnpm',
  48. [
  49. 'run',
  50. 'build-dts',
  51. ...(targets.length
  52. ? ['--environment', `TARGETS:${resolvedTargets.join(',')}`]
  53. : [])
  54. ],
  55. {
  56. stdio: 'inherit'
  57. }
  58. )
  59. }
  60. } finally {
  61. removeCache()
  62. }
  63. }
  64. async function buildAll(targets) {
  65. await runParallel(cpus().length, targets, build)
  66. }
  67. async function runParallel(maxConcurrency, source, iteratorFn) {
  68. const ret = []
  69. const executing = []
  70. for (const item of source) {
  71. const p = Promise.resolve().then(() => iteratorFn(item, source))
  72. ret.push(p)
  73. if (maxConcurrency <= source.length) {
  74. const e = p.then(() => executing.splice(executing.indexOf(e), 1))
  75. executing.push(e)
  76. if (executing.length >= maxConcurrency) {
  77. await Promise.race(executing)
  78. }
  79. }
  80. }
  81. return Promise.all(ret)
  82. }
  83. async function build(target) {
  84. const pkgDir = path.resolve(`packages/${target}`)
  85. const pkg = require(`${pkgDir}/package.json`)
  86. // if this is a full build (no specific targets), ignore private packages
  87. if ((isRelease || !targets.length) && pkg.private) {
  88. return
  89. }
  90. // if building a specific format, do not remove dist.
  91. if (!formats && existsSync(`${pkgDir}/dist`)) {
  92. await fs.rm(`${pkgDir}/dist`, { recursive: true })
  93. }
  94. const env =
  95. (pkg.buildOptions && pkg.buildOptions.env) ||
  96. (devOnly ? 'development' : 'production')
  97. await execa(
  98. 'rollup',
  99. [
  100. '-c',
  101. '--environment',
  102. [
  103. `COMMIT:${commit}`,
  104. `NODE_ENV:${env}`,
  105. `TARGET:${target}`,
  106. formats ? `FORMATS:${formats}` : ``,
  107. prodOnly ? `PROD_ONLY:true` : ``,
  108. sourceMap ? `SOURCE_MAP:true` : ``
  109. ]
  110. .filter(Boolean)
  111. .join(',')
  112. ],
  113. { stdio: 'inherit' }
  114. )
  115. }
  116. function checkAllSizes(targets) {
  117. if (devOnly || (formats && !formats.includes('global'))) {
  118. return
  119. }
  120. console.log()
  121. for (const target of targets) {
  122. checkSize(target)
  123. }
  124. console.log()
  125. }
  126. function checkSize(target) {
  127. const pkgDir = path.resolve(`packages/${target}`)
  128. checkFileSize(`${pkgDir}/dist/${target}.global.prod.js`)
  129. if (!formats || formats.includes('global-runtime')) {
  130. checkFileSize(`${pkgDir}/dist/${target}.runtime.global.prod.js`)
  131. }
  132. }
  133. function checkFileSize(filePath) {
  134. if (!existsSync(filePath)) {
  135. return
  136. }
  137. const file = readFileSync(filePath)
  138. const minSize = (file.length / 1024).toFixed(2) + 'kb'
  139. const gzipped = gzipSync(file)
  140. const gzippedSize = (gzipped.length / 1024).toFixed(2) + 'kb'
  141. const compressed = brotliCompressSync(file)
  142. // @ts-ignore
  143. const compressedSize = (compressed.length / 1024).toFixed(2) + 'kb'
  144. console.log(
  145. `${chalk.gray(
  146. chalk.bold(path.basename(filePath))
  147. )} min:${minSize} / gzip:${gzippedSize} / brotli:${compressedSize}`
  148. )
  149. }