build.mjs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. /*
  2. Produces production builds and stitches together d.ts files.
  3. To specify the package to build, simply pass its name and the desired build
  4. formats to output (defaults to `buildOptions.formats` specified in that package,
  5. or "esm,cjs"):
  6. ```
  7. # name supports fuzzy match. will build all packages with name containing "dom":
  8. nr build dom
  9. # specify the format to output
  10. nr build core --formats cjs
  11. ```
  12. */
  13. // @ts-check
  14. import fs from 'node:fs/promises'
  15. import { existsSync, readFileSync } from 'node:fs'
  16. import path from 'node:path'
  17. import { fileURLToPath } from 'node:url'
  18. import minimist from 'minimist'
  19. import { gzipSync } from 'node:zlib'
  20. import { compress } from 'brotli'
  21. import chalk from 'chalk'
  22. import execa from 'execa'
  23. import { cpus } from 'node:os'
  24. import { createRequire } from 'node:module'
  25. import { targets as allTargets, fuzzyMatchTarget } from './utils.mjs'
  26. const require = createRequire(import.meta.url)
  27. const __dirname = path.dirname(fileURLToPath(import.meta.url))
  28. const args = minimist(process.argv.slice(2))
  29. const targets = args._
  30. const formats = args.formats || args.f
  31. const devOnly = args.devOnly || args.d
  32. const prodOnly = !devOnly && (args.prodOnly || args.p)
  33. const sourceMap = args.sourcemap || args.s
  34. const isRelease = args.release
  35. const buildTypes = args.t || args.types || isRelease
  36. const buildAllMatching = args.all || args.a
  37. const commit = execa.sync('git', ['rev-parse', 'HEAD']).stdout.slice(0, 7)
  38. run()
  39. async function run() {
  40. if (isRelease) {
  41. // remove build cache for release builds to avoid outdated enum values
  42. await fs.rm(path.resolve(__dirname, '../node_modules/.rts2_cache'), {
  43. recursive: true
  44. })
  45. }
  46. if (!targets.length) {
  47. await buildAll(allTargets)
  48. checkAllSizes(allTargets)
  49. } else {
  50. await buildAll(fuzzyMatchTarget(targets, buildAllMatching))
  51. checkAllSizes(fuzzyMatchTarget(targets, buildAllMatching))
  52. }
  53. }
  54. async function buildAll(targets) {
  55. await runParallel(cpus().length, targets, build)
  56. }
  57. async function runParallel(maxConcurrency, source, iteratorFn) {
  58. const ret = []
  59. const executing = []
  60. for (const item of source) {
  61. const p = Promise.resolve().then(() => iteratorFn(item, source))
  62. ret.push(p)
  63. if (maxConcurrency <= source.length) {
  64. const e = p.then(() => executing.splice(executing.indexOf(e), 1))
  65. executing.push(e)
  66. if (executing.length >= maxConcurrency) {
  67. await Promise.race(executing)
  68. }
  69. }
  70. }
  71. return Promise.all(ret)
  72. }
  73. async function build(target) {
  74. const pkgDir = path.resolve(`packages/${target}`)
  75. const pkg = require(`${pkgDir}/package.json`)
  76. // if this is a full build (no specific targets), ignore private packages
  77. if ((isRelease || !targets.length) && pkg.private) {
  78. return
  79. }
  80. // if building a specific format, do not remove dist.
  81. if (!formats && existsSync(`${pkgDir}/dist`)) {
  82. await fs.rm(`${pkgDir}/dist`, { recursive: true })
  83. }
  84. const env =
  85. (pkg.buildOptions && pkg.buildOptions.env) ||
  86. (devOnly ? 'development' : 'production')
  87. await execa(
  88. 'rollup',
  89. [
  90. '-c',
  91. '--environment',
  92. [
  93. `COMMIT:${commit}`,
  94. `NODE_ENV:${env}`,
  95. `TARGET:${target}`,
  96. formats ? `FORMATS:${formats}` : ``,
  97. buildTypes ? `TYPES:true` : ``,
  98. prodOnly ? `PROD_ONLY:true` : ``,
  99. sourceMap ? `SOURCE_MAP:true` : ``
  100. ]
  101. .filter(Boolean)
  102. .join(',')
  103. ],
  104. { stdio: 'inherit' }
  105. )
  106. if (buildTypes && pkg.types) {
  107. console.log()
  108. console.log(
  109. chalk.bold(chalk.yellow(`Rolling up type definitions for ${target}...`))
  110. )
  111. // build types
  112. const { Extractor, ExtractorConfig } = require('@microsoft/api-extractor')
  113. const extractorConfigPath = path.resolve(pkgDir, `api-extractor.json`)
  114. const extractorConfig =
  115. ExtractorConfig.loadFileAndPrepare(extractorConfigPath)
  116. const extractorResult = Extractor.invoke(extractorConfig, {
  117. localBuild: true,
  118. showVerboseMessages: true
  119. })
  120. if (extractorResult.succeeded) {
  121. // concat additional d.ts to rolled-up dts
  122. const typesDir = path.resolve(pkgDir, 'types')
  123. if (existsSync(typesDir)) {
  124. const dtsPath = path.resolve(pkgDir, pkg.types)
  125. const existing = await fs.readFile(dtsPath, 'utf-8')
  126. const typeFiles = await fs.readdir(typesDir)
  127. const toAdd = await Promise.all(
  128. typeFiles.map(file => {
  129. return fs.readFile(path.resolve(typesDir, file), 'utf-8')
  130. })
  131. )
  132. await fs.writeFile(dtsPath, existing + '\n' + toAdd.join('\n'))
  133. }
  134. console.log(
  135. chalk.bold(chalk.green(`API Extractor completed successfully.`))
  136. )
  137. } else {
  138. console.error(
  139. `API Extractor completed with ${extractorResult.errorCount} errors` +
  140. ` and ${extractorResult.warningCount} warnings`
  141. )
  142. process.exitCode = 1
  143. }
  144. await fs.rm(`${pkgDir}/dist/packages`, { recursive: true })
  145. }
  146. }
  147. function checkAllSizes(targets) {
  148. if (devOnly || (formats && !formats.includes('global'))) {
  149. return
  150. }
  151. console.log()
  152. for (const target of targets) {
  153. checkSize(target)
  154. }
  155. console.log()
  156. }
  157. function checkSize(target) {
  158. const pkgDir = path.resolve(`packages/${target}`)
  159. checkFileSize(`${pkgDir}/dist/${target}.global.prod.js`)
  160. if (!formats || formats.includes('global-runtime')) {
  161. checkFileSize(`${pkgDir}/dist/${target}.runtime.global.prod.js`)
  162. }
  163. }
  164. function checkFileSize(filePath) {
  165. if (!existsSync(filePath)) {
  166. return
  167. }
  168. const file = readFileSync(filePath)
  169. const minSize = (file.length / 1024).toFixed(2) + 'kb'
  170. const gzipped = gzipSync(file)
  171. const gzippedSize = (gzipped.length / 1024).toFixed(2) + 'kb'
  172. const compressed = compress(file)
  173. const compressedSize = (compressed?.length || 0 / 1024).toFixed(2) + 'kb'
  174. console.log(
  175. `${chalk.gray(
  176. chalk.bold(path.basename(filePath))
  177. )} min:${minSize} / gzip:${gzippedSize} / brotli:${compressedSize}`
  178. )
  179. }