build.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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 { rolldown } from 'rolldown'
  15. import fs from 'node:fs'
  16. import { parseArgs } from 'node:util'
  17. import { existsSync, readFileSync } from 'node:fs'
  18. import path from 'node:path'
  19. import { brotliCompressSync, gzipSync } from 'node:zlib'
  20. import pico from 'picocolors'
  21. import { targets as allTargets, fuzzyMatchTarget } from './utils.js'
  22. import prettyBytes from 'pretty-bytes'
  23. import { spawnSync } from 'node:child_process'
  24. import { createConfigsForPackage } from './create-rolldown-config.js'
  25. import { scanEnums } from './inline-enums.js'
  26. import { fileURLToPath } from 'node:url'
  27. const __dirname = fileURLToPath(new URL('.', import.meta.url))
  28. const privatePackages = fs.readdirSync('packages-private')
  29. const commit = spawnSync('git', ['rev-parse', '--short=7', 'HEAD'])
  30. .stdout.toString()
  31. .trim()
  32. const { values, positionals: targets } = parseArgs({
  33. allowPositionals: true,
  34. options: {
  35. formats: {
  36. type: 'string',
  37. short: 'f',
  38. },
  39. devOnly: {
  40. type: 'boolean',
  41. short: 'd',
  42. },
  43. prodOnly: {
  44. type: 'boolean',
  45. short: 'p',
  46. },
  47. withTypes: {
  48. type: 'boolean',
  49. short: 't',
  50. },
  51. sourceMap: {
  52. type: 'boolean',
  53. short: 's',
  54. },
  55. release: {
  56. type: 'boolean',
  57. },
  58. all: {
  59. type: 'boolean',
  60. short: 'a',
  61. },
  62. size: {
  63. type: 'boolean',
  64. },
  65. },
  66. })
  67. const {
  68. formats: rawFormats,
  69. all: buildAllMatching,
  70. devOnly,
  71. prodOnly,
  72. withTypes: buildTypes,
  73. sourceMap,
  74. release: isRelease,
  75. size,
  76. } = values
  77. const formats = rawFormats?.split(',')
  78. const sizeDir = path.resolve('temp/size')
  79. run()
  80. async function run() {
  81. if (size) fs.mkdirSync(sizeDir, { recursive: true })
  82. const removeCache = scanEnums()
  83. try {
  84. const resolvedTargets = targets.length
  85. ? fuzzyMatchTarget(targets, buildAllMatching)
  86. : allTargets
  87. await buildAll(resolvedTargets)
  88. if (size) await checkAllSizes(resolvedTargets)
  89. if (buildTypes) {
  90. await import('./build-types.js')
  91. }
  92. } finally {
  93. removeCache()
  94. }
  95. }
  96. /**
  97. * Builds all the targets in parallel.
  98. * @param {Array<string>} targets - An array of targets to build.
  99. * @returns {Promise<void>} - A promise representing the build process.
  100. */
  101. async function buildAll(targets) {
  102. const start = performance.now()
  103. const all = []
  104. let count = 0
  105. for (const t of targets) {
  106. const configs = createConfigsForTarget(t)
  107. if (configs) {
  108. all.push(
  109. Promise.all(
  110. configs.map(c =>
  111. rolldown(c).then(bundle => {
  112. return bundle.write(c.output).then(() => {
  113. // @ts-expect-error
  114. return path.join('packages', t, 'dist', c.output.entryFileNames)
  115. })
  116. }),
  117. ),
  118. ).then(files => {
  119. files.forEach(f => {
  120. count++
  121. console.log(pico.gray('built: ') + pico.green(f))
  122. })
  123. }),
  124. )
  125. }
  126. }
  127. await Promise.all(all)
  128. console.log(
  129. `\n${count} files built in ${(performance.now() - start).toFixed(2)}ms.`,
  130. )
  131. }
  132. /**
  133. * Builds the target.
  134. * @param {string} target - The target to build.
  135. * @returns {import('rolldown').RolldownOptions[] | void} - A promise representing the build process.
  136. */
  137. function createConfigsForTarget(target) {
  138. const pkgBase = privatePackages.includes(target)
  139. ? `packages-private`
  140. : `packages`
  141. const pkgDir = path.resolve(__dirname, `../${pkgBase}/${target}`)
  142. const pkg = JSON.parse(readFileSync(`${pkgDir}/package.json`, 'utf-8'))
  143. // if this is a full build (no specific targets), ignore private packages
  144. if ((isRelease || !targets.length) && pkg.private) {
  145. return
  146. }
  147. // if building a specific format, do not remove dist.
  148. if (!formats && existsSync(`${pkgDir}/dist`)) {
  149. fs.rmSync(`${pkgDir}/dist`, { recursive: true })
  150. }
  151. return createConfigsForPackage({
  152. target,
  153. commit,
  154. // @ts-expect-error
  155. formats,
  156. prodOnly,
  157. devOnly:
  158. (pkg.buildOptions && pkg.buildOptions.env === 'development') || devOnly,
  159. sourceMap,
  160. })
  161. }
  162. /**
  163. * Checks the sizes of all targets.
  164. * @param {string[]} targets - The targets to check sizes for.
  165. * @returns {Promise<void>}
  166. */
  167. async function checkAllSizes(targets) {
  168. if (devOnly || (formats && !formats.includes('global'))) {
  169. return
  170. }
  171. console.log()
  172. for (const target of targets) {
  173. await checkSize(target)
  174. }
  175. console.log()
  176. }
  177. /**
  178. * Checks the size of a target.
  179. * @param {string} target - The target to check the size for.
  180. * @returns {Promise<void>}
  181. */
  182. async function checkSize(target) {
  183. const pkgDir = path.resolve(__dirname, `../packages/${target}`)
  184. await checkFileSize(`${pkgDir}/dist/${target}.global.prod.js`)
  185. if (!formats || formats.includes('global-runtime')) {
  186. await checkFileSize(`${pkgDir}/dist/${target}.runtime.global.prod.js`)
  187. }
  188. }
  189. /**
  190. * Checks the file size.
  191. * @param {string} filePath - The path of the file to check the size for.
  192. * @returns {Promise<void>}
  193. */
  194. async function checkFileSize(filePath) {
  195. if (!existsSync(filePath)) {
  196. return
  197. }
  198. const file = fs.readFileSync(filePath)
  199. const fileName = path.basename(filePath)
  200. const gzipped = gzipSync(file)
  201. const brotli = brotliCompressSync(file)
  202. console.log(
  203. `${pico.gray(pico.bold(fileName))} min:${prettyBytes(
  204. file.length,
  205. )} / gzip:${prettyBytes(gzipped.length)} / brotli:${prettyBytes(
  206. brotli.length,
  207. )}`,
  208. )
  209. if (size)
  210. fs.writeFileSync(
  211. path.resolve(sizeDir, `${fileName}.json`),
  212. JSON.stringify({
  213. file: fileName,
  214. size: file.length,
  215. gzip: gzipped.length,
  216. brotli: brotli.length,
  217. }),
  218. 'utf-8',
  219. )
  220. }