build.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. /**
  86. * @type {string[] | undefined}
  87. */
  88. let formats
  89. let isNegation = false
  90. if (rawFormats) {
  91. isNegation = rawFormats.startsWith('~')
  92. formats = (isNegation ? rawFormats.slice(1) : rawFormats).split('+')
  93. }
  94. const sizeDir = path.resolve('temp/size')
  95. run()
  96. async function run() {
  97. if (size) mkdirSync(sizeDir, { recursive: true })
  98. const removeCache = scanEnums()
  99. try {
  100. const resolvedTargets = targets.length
  101. ? fuzzyMatchTarget(targets, buildAllMatching)
  102. : allTargets
  103. await buildAll(resolvedTargets)
  104. if (size) await checkAllSizes(resolvedTargets)
  105. if (buildTypes) {
  106. await import('./build-types.js')
  107. }
  108. } finally {
  109. removeCache()
  110. }
  111. }
  112. /**
  113. * Builds all the targets in parallel.
  114. * @param {Array<string>} targets - An array of targets to build.
  115. * @returns {Promise<void>} - A promise representing the build process.
  116. */
  117. async function buildAll(targets) {
  118. const start = performance.now()
  119. const all = []
  120. let count = 0
  121. for (const t of targets) {
  122. const configs = createConfigsForTarget(t)
  123. if (configs) {
  124. all.push(
  125. Promise.all(
  126. configs.map(c => {
  127. return rolldown(c).then(bundle => {
  128. // @ts-expect-error
  129. return bundle.write(c.output).then(() => {
  130. // @ts-expect-error
  131. return c.output.file
  132. })
  133. })
  134. }),
  135. ).then(files => {
  136. const from = process.cwd()
  137. files.forEach((/** @type {string} */ f) => {
  138. count++
  139. console.log(
  140. pico.gray('built: ') + pico.green(path.relative(from, f)),
  141. )
  142. })
  143. }),
  144. )
  145. }
  146. }
  147. await Promise.all(all)
  148. console.log(
  149. `\n${count} files built in ${(performance.now() - start).toFixed(2)}ms.`,
  150. )
  151. }
  152. /**
  153. * Builds the target.
  154. * @param {string} target - The target to build.
  155. * @returns {import('rolldown').RolldownOptions[] | void} - A promise representing the build process.
  156. */
  157. function createConfigsForTarget(target) {
  158. const pkgBase = privatePackages.includes(target)
  159. ? `packages-private`
  160. : `packages`
  161. const pkgDir = path.resolve(__dirname, `../${pkgBase}/${target}`)
  162. const pkg = JSON.parse(readFileSync(`${pkgDir}/package.json`, 'utf-8'))
  163. // if this is a full build (no specific targets), ignore private packages
  164. if ((isRelease || !targets.length) && pkg.private) {
  165. return
  166. }
  167. let resolvedFormats
  168. if (formats) {
  169. const pkgFormats = pkg.buildOptions?.formats
  170. if (pkgFormats) {
  171. if (isNegation) {
  172. resolvedFormats = pkgFormats.filter(
  173. (/** @type {string} */ f) => !formats.includes(f),
  174. )
  175. } else {
  176. resolvedFormats = formats.filter(f => pkgFormats.includes(f))
  177. }
  178. }
  179. if (!resolvedFormats.length) {
  180. return
  181. }
  182. }
  183. // if building a specific format, do not remove dist.
  184. if (!formats && existsSync(`${pkgDir}/dist`)) {
  185. rmSync(`${pkgDir}/dist`, { recursive: true })
  186. }
  187. return createConfigsForPackage({
  188. target,
  189. commit,
  190. formats: resolvedFormats,
  191. prodOnly,
  192. devOnly:
  193. (pkg.buildOptions && pkg.buildOptions.env === 'development') || devOnly,
  194. sourceMap,
  195. })
  196. }
  197. /**
  198. * Checks the sizes of all targets.
  199. * @param {string[]} targets - The targets to check sizes for.
  200. * @returns {Promise<void>}
  201. */
  202. async function checkAllSizes(targets) {
  203. if (devOnly || (formats && !formats.includes('global'))) {
  204. return
  205. }
  206. console.log()
  207. for (const target of targets) {
  208. await checkSize(target)
  209. }
  210. console.log()
  211. }
  212. /**
  213. * Checks the size of a target.
  214. * @param {string} target - The target to check the size for.
  215. * @returns {Promise<void>}
  216. */
  217. async function checkSize(target) {
  218. const pkgDir = path.resolve(__dirname, `../packages/${target}`)
  219. await checkFileSize(`${pkgDir}/dist/${target}.global.prod.js`)
  220. if (!formats || formats.includes('global-runtime')) {
  221. await checkFileSize(`${pkgDir}/dist/${target}.runtime.global.prod.js`)
  222. }
  223. }
  224. /**
  225. * Checks the file size.
  226. * @param {string} filePath - The path of the file to check the size for.
  227. * @returns {Promise<void>}
  228. */
  229. async function checkFileSize(filePath) {
  230. if (!existsSync(filePath)) {
  231. return
  232. }
  233. const file = readFileSync(filePath)
  234. const fileName = path.basename(filePath)
  235. const gzipped = gzipSync(file)
  236. const brotli = brotliCompressSync(file)
  237. console.log(
  238. `${pico.gray(pico.bold(fileName))} min:${prettyBytes(
  239. file.length,
  240. )} / gzip:${prettyBytes(gzipped.length)} / brotli:${prettyBytes(
  241. brotli.length,
  242. )}`,
  243. )
  244. if (size)
  245. writeFileSync(
  246. path.resolve(sizeDir, `${fileName}.json`),
  247. JSON.stringify({
  248. file: fileName,
  249. size: file.length,
  250. gzip: gzipped.length,
  251. brotli: brotli.length,
  252. }),
  253. 'utf-8',
  254. )
  255. }