build.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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 fs from 'node:fs'
  17. import { parseArgs } from 'node:util'
  18. import { existsSync, readFileSync } from 'node:fs'
  19. import path from 'node:path'
  20. import { brotliCompressSync, gzipSync } from 'node:zlib'
  21. import pico from 'picocolors'
  22. import { cpus } from 'node:os'
  23. import { targets as allTargets, exec, fuzzyMatchTarget } from './utils.js'
  24. import { scanEnums } from './inline-enums.js'
  25. import prettyBytes from 'pretty-bytes'
  26. import { spawnSync } from 'node:child_process'
  27. const commit = spawnSync('git', ['rev-parse', '--short=7', 'HEAD'])
  28. .stdout.toString()
  29. .trim()
  30. const { values, positionals: targets } = parseArgs({
  31. allowPositionals: true,
  32. options: {
  33. formats: {
  34. type: 'string',
  35. short: 'f',
  36. },
  37. devOnly: {
  38. type: 'boolean',
  39. short: 'd',
  40. },
  41. prodOnly: {
  42. type: 'boolean',
  43. short: 'p',
  44. },
  45. withTypes: {
  46. type: 'boolean',
  47. short: 't',
  48. },
  49. sourceMap: {
  50. type: 'boolean',
  51. short: 's',
  52. },
  53. release: {
  54. type: 'boolean',
  55. },
  56. all: {
  57. type: 'boolean',
  58. short: 'a',
  59. },
  60. size: {
  61. type: 'boolean',
  62. },
  63. },
  64. })
  65. const {
  66. formats,
  67. all: buildAllMatching,
  68. devOnly,
  69. prodOnly,
  70. withTypes: buildTypes,
  71. sourceMap,
  72. release: isRelease,
  73. size: writeSize,
  74. } = values
  75. const sizeDir = path.resolve('temp/size')
  76. run()
  77. async function run() {
  78. if (writeSize) fs.mkdirSync(sizeDir, { recursive: true })
  79. const removeCache = scanEnums()
  80. try {
  81. const resolvedTargets = targets.length
  82. ? fuzzyMatchTarget(targets, buildAllMatching)
  83. : allTargets
  84. await buildAll(resolvedTargets)
  85. await checkAllSizes(resolvedTargets)
  86. if (buildTypes) {
  87. await exec(
  88. 'pnpm',
  89. [
  90. 'run',
  91. 'build-dts',
  92. ...(targets.length
  93. ? ['--environment', `TARGETS:${resolvedTargets.join(',')}`]
  94. : []),
  95. ],
  96. {
  97. stdio: 'inherit',
  98. },
  99. )
  100. }
  101. } finally {
  102. removeCache()
  103. }
  104. }
  105. /**
  106. * Builds all the targets in parallel.
  107. * @param {Array<string>} targets - An array of targets to build.
  108. * @returns {Promise<void>} - A promise representing the build process.
  109. */
  110. async function buildAll(targets) {
  111. await runParallel(cpus().length, targets, build)
  112. }
  113. /**
  114. * Runs iterator function in parallel.
  115. * @template T - The type of items in the data source
  116. * @param {number} maxConcurrency - The maximum concurrency.
  117. * @param {Array<T>} source - The data source
  118. * @param {(item: T) => Promise<void>} iteratorFn - The iteratorFn
  119. * @returns {Promise<void[]>} - A Promise array containing all iteration results.
  120. */
  121. async function runParallel(maxConcurrency, source, iteratorFn) {
  122. /**@type {Promise<void>[]} */
  123. const ret = []
  124. /**@type {Promise<void>[]} */
  125. const executing = []
  126. for (const item of source) {
  127. const p = Promise.resolve().then(() => iteratorFn(item))
  128. ret.push(p)
  129. if (maxConcurrency <= source.length) {
  130. const e = p.then(() => {
  131. executing.splice(executing.indexOf(e), 1)
  132. })
  133. executing.push(e)
  134. if (executing.length >= maxConcurrency) {
  135. await Promise.race(executing)
  136. }
  137. }
  138. }
  139. return Promise.all(ret)
  140. }
  141. const privatePackages = fs.readdirSync('packages-private')
  142. /**
  143. * Builds the target.
  144. * @param {string} target - The target to build.
  145. * @returns {Promise<void>} - A promise representing the build process.
  146. */
  147. async function build(target) {
  148. const pkgBase = privatePackages.includes(target)
  149. ? `packages-private`
  150. : `packages`
  151. const pkgDir = path.resolve(`${pkgBase}/${target}`)
  152. const pkg = JSON.parse(readFileSync(`${pkgDir}/package.json`, 'utf-8'))
  153. // if this is a full build (no specific targets), ignore private packages
  154. if ((isRelease || !targets.length) && pkg.private) {
  155. return
  156. }
  157. // if building a specific format, do not remove dist.
  158. if (!formats && existsSync(`${pkgDir}/dist`)) {
  159. fs.rmSync(`${pkgDir}/dist`, { recursive: true })
  160. }
  161. const env =
  162. (pkg.buildOptions && pkg.buildOptions.env) ||
  163. (devOnly ? 'development' : 'production')
  164. await exec(
  165. 'rollup',
  166. [
  167. '-c',
  168. '--environment',
  169. [
  170. `COMMIT:${commit}`,
  171. `NODE_ENV:${env}`,
  172. `TARGET:${target}`,
  173. formats ? `FORMATS:${formats}` : ``,
  174. prodOnly ? `PROD_ONLY:true` : ``,
  175. sourceMap ? `SOURCE_MAP:true` : ``,
  176. ]
  177. .filter(Boolean)
  178. .join(','),
  179. ],
  180. { stdio: 'inherit' },
  181. )
  182. }
  183. /**
  184. * Checks the sizes of all targets.
  185. * @param {string[]} targets - The targets to check sizes for.
  186. * @returns {Promise<void>}
  187. */
  188. async function checkAllSizes(targets) {
  189. if (devOnly || (formats && !formats.includes('global'))) {
  190. return
  191. }
  192. console.log()
  193. for (const target of targets) {
  194. await checkSize(target)
  195. }
  196. console.log()
  197. }
  198. /**
  199. * Checks the size of a target.
  200. * @param {string} target - The target to check the size for.
  201. * @returns {Promise<void>}
  202. */
  203. async function checkSize(target) {
  204. const pkgDir = path.resolve(`packages/${target}`)
  205. await checkFileSize(`${pkgDir}/dist/${target}.global.prod.js`)
  206. if (!formats || formats.includes('global-runtime')) {
  207. await checkFileSize(`${pkgDir}/dist/${target}.runtime.global.prod.js`)
  208. }
  209. }
  210. /**
  211. * Checks the file size.
  212. * @param {string} filePath - The path of the file to check the size for.
  213. * @returns {Promise<void>}
  214. */
  215. async function checkFileSize(filePath) {
  216. if (!existsSync(filePath)) {
  217. return
  218. }
  219. const file = fs.readFileSync(filePath)
  220. const fileName = path.basename(filePath)
  221. const gzipped = gzipSync(file)
  222. const brotli = brotliCompressSync(file)
  223. console.log(
  224. `${pico.gray(pico.bold(fileName))} min:${prettyBytes(
  225. file.length,
  226. )} / gzip:${prettyBytes(gzipped.length)} / brotli:${prettyBytes(
  227. brotli.length,
  228. )}`,
  229. )
  230. if (writeSize)
  231. fs.writeFileSync(
  232. path.resolve(sizeDir, `${fileName}.json`),
  233. JSON.stringify({
  234. file: fileName,
  235. size: file.length,
  236. gzip: gzipped.length,
  237. brotli: brotli.length,
  238. }),
  239. 'utf-8',
  240. )
  241. }