build.js 6.7 KB

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