create-rolldown-config.js 11 KB

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