create-rolldown-config.js 12 KB

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