build.js 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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 } from 'node:zlib'
  19. import { compress } from 'brotli'
  20. import chalk from 'chalk'
  21. import execa from 'execa'
  22. import { cpus } from 'node:os'
  23. import { createRequire } from 'node:module'
  24. import { targets as allTargets, fuzzyMatchTarget } from './utils.js'
  25. import { scanEnums } from './const-enum.js'
  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 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. if (!targets.length) {
  41. await buildAll(allTargets)
  42. checkAllSizes(allTargets)
  43. } else {
  44. await buildAll(fuzzyMatchTarget(targets, buildAllMatching))
  45. checkAllSizes(fuzzyMatchTarget(targets, buildAllMatching))
  46. }
  47. } finally {
  48. removeCache()
  49. }
  50. }
  51. async function buildAll(targets) {
  52. await runParallel(cpus().length, targets, build)
  53. }
  54. async function runParallel(maxConcurrency, source, iteratorFn) {
  55. const ret = []
  56. const executing = []
  57. for (const item of source) {
  58. const p = Promise.resolve().then(() => iteratorFn(item, source))
  59. ret.push(p)
  60. if (maxConcurrency <= source.length) {
  61. const e = p.then(() => executing.splice(executing.indexOf(e), 1))
  62. executing.push(e)
  63. if (executing.length >= maxConcurrency) {
  64. await Promise.race(executing)
  65. }
  66. }
  67. }
  68. return Promise.all(ret)
  69. }
  70. async function build(target) {
  71. const pkgDir = path.resolve(`packages/${target}`)
  72. const pkg = require(`${pkgDir}/package.json`)
  73. // if this is a full build (no specific targets), ignore private packages
  74. if ((isRelease || !targets.length) && pkg.private) {
  75. return
  76. }
  77. // if building a specific format, do not remove dist.
  78. if (!formats && existsSync(`${pkgDir}/dist`)) {
  79. await fs.rm(`${pkgDir}/dist`, { recursive: true })
  80. }
  81. const env =
  82. (pkg.buildOptions && pkg.buildOptions.env) ||
  83. (devOnly ? 'development' : 'production')
  84. await execa(
  85. 'rollup',
  86. [
  87. '-c',
  88. '--environment',
  89. [
  90. `COMMIT:${commit}`,
  91. `NODE_ENV:${env}`,
  92. `TARGET:${target}`,
  93. formats ? `FORMATS:${formats}` : ``,
  94. prodOnly ? `PROD_ONLY:true` : ``,
  95. sourceMap ? `SOURCE_MAP:true` : ``
  96. ]
  97. .filter(Boolean)
  98. .join(',')
  99. ],
  100. { stdio: 'inherit' }
  101. )
  102. }
  103. function checkAllSizes(targets) {
  104. if (devOnly || (formats && !formats.includes('global'))) {
  105. return
  106. }
  107. console.log()
  108. for (const target of targets) {
  109. checkSize(target)
  110. }
  111. console.log()
  112. }
  113. function checkSize(target) {
  114. const pkgDir = path.resolve(`packages/${target}`)
  115. checkFileSize(`${pkgDir}/dist/${target}.global.prod.js`)
  116. if (!formats || formats.includes('global-runtime')) {
  117. checkFileSize(`${pkgDir}/dist/${target}.runtime.global.prod.js`)
  118. }
  119. }
  120. function checkFileSize(filePath) {
  121. if (!existsSync(filePath)) {
  122. return
  123. }
  124. const file = readFileSync(filePath)
  125. const minSize = (file.length / 1024).toFixed(2) + 'kb'
  126. const gzipped = gzipSync(file)
  127. const gzippedSize = (gzipped.length / 1024).toFixed(2) + 'kb'
  128. const compressed = compress(file)
  129. // @ts-ignore
  130. const compressedSize = (compressed.length / 1024).toFixed(2) + 'kb'
  131. console.log(
  132. `${chalk.gray(
  133. chalk.bold(path.basename(filePath))
  134. )} min:${minSize} / gzip:${gzippedSize} / brotli:${compressedSize}`
  135. )
  136. }