create-rolldown-config.js 12 KB

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