build.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. yarn build dom
  9. # specify the format to output
  10. yarn build core --formats cjs
  11. ```
  12. */
  13. const fs = require('fs-extra')
  14. const path = require('path')
  15. const chalk = require('chalk')
  16. const execa = require('execa')
  17. const { gzipSync } = require('zlib')
  18. const { compress } = require('brotli')
  19. const { targets: allTargets, fuzzyMatchTarget } = require('./utils')
  20. const args = require('minimist')(process.argv.slice(2))
  21. const targets = args._
  22. const formats = args.formats || args.f
  23. const devOnly = args.devOnly || args.d
  24. const prodOnly = !devOnly && (args.prodOnly || args.p)
  25. const sourceMap = args.sourcemap || args.s
  26. const isRelease = args.release
  27. const buildTypes = args.t || args.types || isRelease
  28. const buildAllMatching = args.all || args.a
  29. const commit = execa.sync('git', ['rev-parse', 'HEAD']).stdout.slice(0, 7)
  30. run()
  31. async function run() {
  32. if (isRelease) {
  33. // remove build cache for release builds to avoid outdated enum values
  34. await fs.remove(path.resolve(__dirname, '../node_modules/.rts2_cache'))
  35. }
  36. if (!targets.length) {
  37. await buildAll(allTargets)
  38. checkAllSizes(allTargets)
  39. } else {
  40. await buildAll(fuzzyMatchTarget(targets, buildAllMatching))
  41. checkAllSizes(fuzzyMatchTarget(targets, buildAllMatching))
  42. }
  43. }
  44. async function buildAll(targets) {
  45. for (const target of targets) {
  46. await build(target)
  47. }
  48. }
  49. async function build(target) {
  50. const pkgDir = path.resolve(`packages/${target}`)
  51. const pkg = require(`${pkgDir}/package.json`)
  52. // only build published packages for release
  53. if (isRelease && pkg.private) {
  54. return
  55. }
  56. // if building a specific format, do not remove dist.
  57. if (!formats) {
  58. await fs.remove(`${pkgDir}/dist`)
  59. }
  60. const env =
  61. (pkg.buildOptions && pkg.buildOptions.env) ||
  62. (devOnly ? 'development' : 'production')
  63. await execa(
  64. 'rollup',
  65. [
  66. '-c',
  67. '--environment',
  68. [
  69. `COMMIT:${commit}`,
  70. `NODE_ENV:${env}`,
  71. `TARGET:${target}`,
  72. formats ? `FORMATS:${formats}` : ``,
  73. buildTypes ? `TYPES:true` : ``,
  74. prodOnly ? `PROD_ONLY:true` : ``,
  75. sourceMap ? `SOURCE_MAP:true` : ``
  76. ]
  77. .filter(Boolean)
  78. .join(',')
  79. ],
  80. { stdio: 'inherit' }
  81. )
  82. if (buildTypes && pkg.types) {
  83. console.log()
  84. console.log(
  85. chalk.bold(chalk.yellow(`Rolling up type definitions for ${target}...`))
  86. )
  87. // build types
  88. const { Extractor, ExtractorConfig } = require('@microsoft/api-extractor')
  89. const extractorConfigPath = path.resolve(pkgDir, `api-extractor.json`)
  90. const extractorConfig = ExtractorConfig.loadFileAndPrepare(
  91. extractorConfigPath
  92. )
  93. const extractorResult = Extractor.invoke(extractorConfig, {
  94. localBuild: true,
  95. showVerboseMessages: true
  96. })
  97. if (extractorResult.succeeded) {
  98. // concat additional d.ts to rolled-up dts
  99. const typesDir = path.resolve(pkgDir, 'types')
  100. if (await fs.exists(typesDir)) {
  101. const dtsPath = path.resolve(pkgDir, pkg.types)
  102. const existing = await fs.readFile(dtsPath, 'utf-8')
  103. const typeFiles = await fs.readdir(typesDir)
  104. const toAdd = await Promise.all(
  105. typeFiles.map(file => {
  106. return fs.readFile(path.resolve(typesDir, file), 'utf-8')
  107. })
  108. )
  109. await fs.writeFile(dtsPath, existing + '\n' + toAdd.join('\n'))
  110. }
  111. console.log(
  112. chalk.bold(chalk.green(`API Extractor completed successfully.`))
  113. )
  114. } else {
  115. console.error(
  116. `API Extractor completed with ${extractorResult.errorCount} errors` +
  117. ` and ${extractorResult.warningCount} warnings`
  118. )
  119. process.exitCode = 1
  120. }
  121. await fs.remove(`${pkgDir}/dist/packages`)
  122. }
  123. }
  124. function checkAllSizes(targets) {
  125. if (devOnly) {
  126. return
  127. }
  128. console.log()
  129. for (const target of targets) {
  130. checkSize(target)
  131. }
  132. console.log()
  133. }
  134. function checkSize(target) {
  135. const pkgDir = path.resolve(`packages/${target}`)
  136. checkFileSize(`${pkgDir}/dist/${target}.global.prod.js`)
  137. }
  138. function checkFileSize(filePath) {
  139. if (!fs.existsSync(filePath)) {
  140. return
  141. }
  142. const file = fs.readFileSync(filePath)
  143. const minSize = (file.length / 1024).toFixed(2) + 'kb'
  144. const gzipped = gzipSync(file)
  145. const gzippedSize = (gzipped.length / 1024).toFixed(2) + 'kb'
  146. const compressed = compress(file)
  147. const compressedSize = (compressed.length / 1024).toFixed(2) + 'kb'
  148. console.log(
  149. `${chalk.gray(
  150. chalk.bold(path.basename(filePath))
  151. )} min:${minSize} / gzip:${gzippedSize} / brotli:${compressedSize}`
  152. )
  153. }