create-rolldown-config.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. // @ts-check
  2. import assert from 'node:assert/strict'
  3. import { createRequire } from 'node:module'
  4. import { fileURLToPath } from 'node:url'
  5. import path from 'node:path'
  6. import { replacePlugin } from 'rolldown/experimental'
  7. import pico from 'picocolors'
  8. import polyfillNode from '@rolldown/plugin-node-polyfills'
  9. import { entries } from './aliases.js'
  10. import { inlineEnums } from './inline-enums.js'
  11. import { minify as minifySwc } from '@swc/core'
  12. const require = createRequire(import.meta.url)
  13. const __dirname = fileURLToPath(new URL('.', import.meta.url))
  14. const masterVersion = require('../package.json').version
  15. const consolidatePkg = require('@vue/consolidate/package.json')
  16. const packagesDir = path.resolve(__dirname, '../packages')
  17. /** @typedef {'cjs' | 'esm-bundler' | 'global' | 'global-runtime' | 'esm-browser' | 'esm-bundler-runtime' | 'esm-browser-runtime'} PackageFormat */
  18. /**
  19. * @param {{
  20. * target: string
  21. * commit: string
  22. * formats?: PackageFormat[]
  23. * devOnly?: boolean
  24. * prodOnly?: boolean
  25. * sourceMap?: boolean
  26. * localDev?: boolean
  27. * inlineDeps?: boolean
  28. * }} options
  29. */
  30. export function createConfigsForPackage({
  31. target,
  32. commit,
  33. formats,
  34. devOnly = false,
  35. prodOnly = false,
  36. sourceMap = false,
  37. localDev = false,
  38. inlineDeps = false,
  39. }) {
  40. const [enumPlugin, enumDefines] = localDev ? [] : inlineEnums()
  41. const packageDir = path.resolve(packagesDir, target)
  42. const resolve = (/** @type {string} */ p) => path.resolve(packageDir, p)
  43. const pkg = require(resolve(`package.json`))
  44. const packageOptions = pkg.buildOptions || {}
  45. const name = packageOptions.filename || path.basename(packageDir)
  46. /** @type {Record<PackageFormat, import('rolldown').OutputOptions>} */
  47. const outputConfigs = {
  48. 'esm-bundler': {
  49. file: `${name}.esm-bundler.js`,
  50. format: 'es',
  51. },
  52. 'esm-browser': {
  53. file: `${name}.esm-browser.js`,
  54. format: 'es',
  55. },
  56. cjs: {
  57. file: `${name}.cjs.js`,
  58. format: 'cjs',
  59. },
  60. global: {
  61. file: `${name}.global.js`,
  62. format: 'iife',
  63. },
  64. // runtime-only builds, for main "vue" package only
  65. 'esm-bundler-runtime': {
  66. file: `${name}.runtime.esm-bundler.js`,
  67. format: 'es',
  68. },
  69. 'esm-browser-runtime': {
  70. file: `${name}.runtime.esm-browser.js`,
  71. format: 'es',
  72. },
  73. 'global-runtime': {
  74. file: `${name}.runtime.global.js`,
  75. format: 'iife',
  76. },
  77. }
  78. const resolvedFormats = (
  79. formats ||
  80. packageOptions.formats || ['esm-bundler', 'cjs']
  81. ).filter(format => outputConfigs[format])
  82. const packageConfigs = prodOnly
  83. ? []
  84. : resolvedFormats.map(format => createConfig(format, outputConfigs[format]))
  85. if (!devOnly) {
  86. resolvedFormats.forEach(format => {
  87. if (packageOptions.prod === false) {
  88. return
  89. }
  90. if (format === 'cjs') {
  91. packageConfigs.push(createProductionConfig(format))
  92. }
  93. if (/^(global|esm-browser)(-runtime)?/.test(format)) {
  94. packageConfigs.push(createMinifiedConfig(format))
  95. }
  96. })
  97. }
  98. /**
  99. *
  100. * @param {PackageFormat} format
  101. * @param {import('rolldown').OutputOptions} output
  102. * @param {import('rolldown').Plugin[]} plugins
  103. * @returns {import('rolldown').RolldownOptions}
  104. */
  105. function createConfig(format, output, plugins = []) {
  106. if (!output) {
  107. console.error(pico.yellow(`invalid format: "${format}"`))
  108. process.exit(1)
  109. }
  110. output.dir = resolve('dist')
  111. const isProductionBuild = /\.prod\.js$/.test(String(output.file) || '')
  112. const isBundlerESMBuild = /esm-bundler/.test(format)
  113. const isBrowserESMBuild = /esm-browser/.test(format)
  114. const isServerRenderer = name === 'server-renderer'
  115. const isCJSBuild = format === 'cjs'
  116. const isGlobalBuild = /global/.test(format)
  117. const isCompatPackage =
  118. pkg.name === '@vue/compat' || pkg.name === '@vue/compat-canary'
  119. const isCompatBuild = !!packageOptions.compat
  120. const isBrowserBuild =
  121. (isGlobalBuild || isBrowserESMBuild || isBundlerESMBuild) &&
  122. !packageOptions.enableNonBrowserBranches
  123. output.banner = `/**
  124. * ${pkg.name} v${masterVersion}
  125. * (c) 2018-present Yuxi (Evan) You and Vue contributors
  126. * @license MIT
  127. **/`
  128. output.exports = isCompatPackage ? 'auto' : 'named'
  129. if (isCJSBuild) {
  130. output.esModule = true
  131. }
  132. output.sourcemap = sourceMap
  133. output.externalLiveBindings = false
  134. // https://github.com/rollup/rollup/pull/5380
  135. // @ts-expect-error Not supported yet
  136. output.reexportProtoFromExternal = false
  137. if (isGlobalBuild) {
  138. output.name = packageOptions.name
  139. }
  140. let entryFile = /runtime$/.test(format) ? `src/runtime.ts` : `src/index.ts`
  141. // the compat build needs both default AND named exports. This will cause
  142. // Rollup to complain for non-ESM targets, so we use separate entries for
  143. // esm vs. non-esm builds.
  144. if (isCompatPackage && (isBrowserESMBuild || isBundlerESMBuild)) {
  145. entryFile = /runtime$/.test(format)
  146. ? `src/esm-runtime.ts`
  147. : `src/esm-index.ts`
  148. }
  149. function resolveDefine() {
  150. /** @type {Record<string, string>} */
  151. const defines = {
  152. __COMMIT__: `"${commit}"`,
  153. __VERSION__: `"${masterVersion}"`,
  154. // this is only used during Vue's internal tests
  155. __TEST__: `false`,
  156. // If the build is expected to run directly in the browser (global / esm builds)
  157. __BROWSER__: String(isBrowserBuild),
  158. __GLOBAL__: String(isGlobalBuild),
  159. __ESM_BUNDLER__: String(isBundlerESMBuild),
  160. __ESM_BROWSER__: String(isBrowserESMBuild),
  161. // is targeting Node (SSR)?
  162. __CJS__: String(isCJSBuild),
  163. // need SSR-specific branches?
  164. __SSR__: String(isCJSBuild || isBundlerESMBuild || isServerRenderer),
  165. // 2.x compat build
  166. __COMPAT__: String(isCompatBuild),
  167. // feature flags
  168. __FEATURE_SUSPENSE__: `true`,
  169. __FEATURE_OPTIONS_API__: isBundlerESMBuild
  170. ? `__VUE_OPTIONS_API__`
  171. : `true`,
  172. __FEATURE_PROD_DEVTOOLS__: isBundlerESMBuild
  173. ? `__VUE_PROD_DEVTOOLS__`
  174. : `false`,
  175. __FEATURE_PROD_HYDRATION_MISMATCH_DETAILS__: isBundlerESMBuild
  176. ? `__VUE_PROD_HYDRATION_MISMATCH_DETAILS__`
  177. : `false`,
  178. }
  179. if (!isBundlerESMBuild) {
  180. // hard coded dev/prod builds
  181. defines.__DEV__ = String(!isProductionBuild)
  182. }
  183. // allow inline overrides like
  184. //__RUNTIME_COMPILE__=true pnpm build runtime-core
  185. Object.keys(defines).forEach(key => {
  186. if (key in process.env) {
  187. const value = process.env[key]
  188. assert(typeof value === 'string')
  189. defines[key] = value
  190. }
  191. })
  192. return defines
  193. }
  194. // define is a bit strict and only allows literal json or identifiers
  195. // so we still need replace plugin in some cases
  196. function resolveReplace() {
  197. /** @type {Record<string, string>} */
  198. const replacements = { ...enumDefines }
  199. if (isBundlerESMBuild) {
  200. Object.assign(replacements, {
  201. // preserve to be handled by bundlers
  202. __DEV__: `!!(process.env.NODE_ENV !== 'production')`,
  203. })
  204. }
  205. // for compiler-sfc browser build inlined deps
  206. if (isBrowserESMBuild && name === 'compiler-sfc') {
  207. Object.assign(replacements, {
  208. 'process.env': '({})',
  209. 'process.platform': '""',
  210. 'process.stdout': 'null',
  211. })
  212. }
  213. if (Object.keys(replacements).length) {
  214. return [replacePlugin(replacements)]
  215. } else {
  216. return []
  217. }
  218. }
  219. function resolveExternal() {
  220. const treeShakenDeps = [
  221. 'source-map-js',
  222. '@babel/parser',
  223. 'estree-walker',
  224. 'entities/lib/decode.js',
  225. ]
  226. // we are bundling forked consolidate.js in compiler-sfc which dynamically
  227. // requires a ton of template engines which should be ignored.
  228. let cjsIgnores = []
  229. if (
  230. pkg.name === '@vue/compiler-sfc' ||
  231. pkg.name === '@vue/compiler-sfc-canary'
  232. ) {
  233. cjsIgnores = [
  234. ...Object.keys(consolidatePkg.devDependencies),
  235. 'vm',
  236. 'crypto',
  237. 'react-dom/server',
  238. 'teacup/lib/express',
  239. 'arc-templates/dist/es5',
  240. 'then-pug',
  241. 'then-jade',
  242. ]
  243. }
  244. if (isGlobalBuild || isBrowserESMBuild || isCompatPackage || inlineDeps) {
  245. if (!packageOptions.enableNonBrowserBranches) {
  246. // normal browser builds - non-browser only imports are tree-shaken,
  247. // they are only listed here to suppress warnings.
  248. return treeShakenDeps
  249. } else {
  250. return cjsIgnores
  251. }
  252. } else {
  253. // Node / esm-bundler builds.
  254. // externalize all direct deps unless it's the compat build.
  255. return [
  256. ...Object.keys(pkg.dependencies || {}),
  257. ...Object.keys(pkg.peerDependencies || {}),
  258. // for @vue/compiler-sfc / server-renderer
  259. ...['path', 'url', 'stream'],
  260. // somehow these throw warnings for runtime-* package builds
  261. ...treeShakenDeps,
  262. ...cjsIgnores,
  263. ]
  264. }
  265. }
  266. function resolveNodePlugins() {
  267. const nodePlugins =
  268. (format === 'cjs' && Object.keys(pkg.devDependencies || {}).length) ||
  269. packageOptions.enableNonBrowserBranches
  270. ? [...(format === 'cjs' ? [] : [polyfillNode()])]
  271. : []
  272. return nodePlugins
  273. }
  274. return {
  275. input: resolve(entryFile),
  276. // Global and Browser ESM builds inlines everything so that they can be
  277. // used alone.
  278. external: resolveExternal(),
  279. define: resolveDefine(),
  280. platform: format === 'cjs' ? 'node' : 'browser',
  281. resolve: {
  282. alias: entries,
  283. },
  284. // @ts-expect-error rollup's Plugin type incompatible w/ rolldown's vendored Plugin type
  285. plugins: [
  286. ...(localDev ? [] : [enumPlugin]),
  287. ...resolveReplace(),
  288. ...resolveNodePlugins(),
  289. ...plugins,
  290. ],
  291. output,
  292. onwarn: (msg, warn) => {
  293. if (msg.code !== 'CIRCULAR_DEPENDENCY') {
  294. warn(msg)
  295. }
  296. },
  297. treeshake: {
  298. // https://github.com/rolldown/rolldown/issues/1917
  299. moduleSideEffects: false,
  300. },
  301. }
  302. }
  303. function createProductionConfig(/** @type {PackageFormat} */ format) {
  304. return createConfig(format, {
  305. file: `${name}.${format}.prod.js`,
  306. format: outputConfigs[format].format,
  307. })
  308. }
  309. function createMinifiedConfig(/** @type {PackageFormat} */ format) {
  310. return createConfig(
  311. format,
  312. {
  313. file: String(outputConfigs[format].file).replace(/\.js$/, '.prod.js'),
  314. format: outputConfigs[format].format,
  315. // minify: true,
  316. },
  317. [
  318. {
  319. name: 'swc-minify',
  320. async renderChunk(
  321. contents,
  322. _,
  323. {
  324. format,
  325. sourcemap,
  326. // @ts-expect-error not supported yet
  327. sourcemapExcludeSources,
  328. },
  329. ) {
  330. const { code, map } = await minifySwc(contents, {
  331. module: format === 'es',
  332. compress: {
  333. ecma: 2016,
  334. pure_getters: true,
  335. },
  336. safari10: true,
  337. mangle: true,
  338. sourceMap: !!sourcemap,
  339. inlineSourcesContent: !sourcemapExcludeSources,
  340. })
  341. return { code, map: map || null }
  342. },
  343. },
  344. ],
  345. )
  346. }
  347. return packageConfigs
  348. }