2
0

build.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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. let resolvedFormats
  158. if (formats) {
  159. const isNegation = formats.startsWith('~')
  160. resolvedFormats = (isNegation ? formats.slice(1) : formats).split('+')
  161. const pkgFormats = pkg.buildOptions?.formats
  162. if (pkgFormats) {
  163. if (isNegation) {
  164. resolvedFormats = pkgFormats.filter(f => !resolvedFormats.includes(f))
  165. } else {
  166. resolvedFormats = resolvedFormats.filter(f => pkgFormats.includes(f))
  167. }
  168. }
  169. if (!resolvedFormats.length) {
  170. return
  171. }
  172. }
  173. // if building a specific format, do not remove dist.
  174. if (!formats && existsSync(`${pkgDir}/dist`)) {
  175. fs.rmSync(`${pkgDir}/dist`, { recursive: true })
  176. }
  177. const env =
  178. (pkg.buildOptions && pkg.buildOptions.env) ||
  179. (devOnly ? 'development' : 'production')
  180. await exec(
  181. 'rollup',
  182. [
  183. '-c',
  184. '--environment',
  185. [
  186. `COMMIT:${commit}`,
  187. `NODE_ENV:${env}`,
  188. `TARGET:${target}`,
  189. resolvedFormats ? `FORMATS:${resolvedFormats.join('+')}` : ``,
  190. prodOnly ? `PROD_ONLY:true` : ``,
  191. sourceMap ? `SOURCE_MAP:true` : ``,
  192. ]
  193. .filter(Boolean)
  194. .join(','),
  195. ],
  196. { stdio: 'inherit' },
  197. )
  198. }
  199. /**
  200. * Checks the sizes of all targets.
  201. * @param {string[]} targets - The targets to check sizes for.
  202. * @returns {Promise<void>}
  203. */
  204. async function checkAllSizes(targets) {
  205. if (
  206. devOnly ||
  207. (formats && (formats.startsWith('~') || !formats.includes('global')))
  208. ) {
  209. return
  210. }
  211. console.log()
  212. for (const target of targets) {
  213. await checkSize(target)
  214. }
  215. console.log()
  216. }
  217. /**
  218. * Checks the size of a target.
  219. * @param {string} target - The target to check the size for.
  220. * @returns {Promise<void>}
  221. */
  222. async function checkSize(target) {
  223. const pkgDir = path.resolve(`packages/${target}`)
  224. await checkFileSize(`${pkgDir}/dist/${target}.global.prod.js`)
  225. if (!formats || formats.includes('global-runtime')) {
  226. await checkFileSize(`${pkgDir}/dist/${target}.runtime.global.prod.js`)
  227. }
  228. }
  229. /**
  230. * Checks the file size.
  231. * @param {string} filePath - The path of the file to check the size for.
  232. * @returns {Promise<void>}
  233. */
  234. async function checkFileSize(filePath) {
  235. if (!existsSync(filePath)) {
  236. return
  237. }
  238. const file = fs.readFileSync(filePath)
  239. const fileName = path.basename(filePath)
  240. const gzipped = gzipSync(file)
  241. const brotli = brotliCompressSync(file)
  242. console.log(
  243. `${pico.gray(pico.bold(fileName))} min:${prettyBytes(
  244. file.length,
  245. )} / gzip:${prettyBytes(gzipped.length)} / brotli:${prettyBytes(
  246. brotli.length,
  247. )}`,
  248. )
  249. if (writeSize)
  250. fs.writeFileSync(
  251. path.resolve(sizeDir, `${fileName}.json`),
  252. JSON.stringify({
  253. file: fileName,
  254. size: file.length,
  255. gzip: gzipped.length,
  256. brotli: brotli.length,
  257. }),
  258. 'utf-8',
  259. )
  260. }