create-rolldown-config.js 12 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/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.
  160. // we use separate entries for esm vs. non-esm builds.
  161. if (isCompatPackage && (isBrowserESMBuild || isBundlerESMBuild)) {
  162. entryFile = `esm-${entryFile}`
  163. }
  164. entryFile = 'src/' + entryFile
  165. function resolveDefine() {
  166. /** @type {Record<string, string>} */
  167. const defines = {
  168. __COMMIT__: `"${commit}"`,
  169. __VERSION__: `"${masterVersion}"`,
  170. // this is only used during Vue's internal tests
  171. __TEST__: `false`,
  172. // If the build is expected to run directly in the browser (global / esm builds)
  173. __BROWSER__: String(isBrowserBuild),
  174. __GLOBAL__: String(isGlobalBuild),
  175. __ESM_BUNDLER__: String(isBundlerESMBuild),
  176. __ESM_BROWSER__: String(isBrowserESMBuild),
  177. // is targeting Node (SSR)?
  178. __CJS__: String(isCJSBuild),
  179. // need SSR-specific branches?
  180. __SSR__: String(isCJSBuild || isBundlerESMBuild || isServerRenderer),
  181. // 2.x compat build
  182. __COMPAT__: String(isCompatBuild),
  183. // feature flags
  184. __FEATURE_SUSPENSE__: `true`,
  185. __FEATURE_OPTIONS_API__: isBundlerESMBuild
  186. ? `__VUE_OPTIONS_API__`
  187. : `true`,
  188. __FEATURE_PROD_DEVTOOLS__: isBundlerESMBuild
  189. ? `__VUE_PROD_DEVTOOLS__`
  190. : `false`,
  191. __FEATURE_PROD_HYDRATION_MISMATCH_DETAILS__: isBundlerESMBuild
  192. ? `__VUE_PROD_HYDRATION_MISMATCH_DETAILS__`
  193. : `false`,
  194. }
  195. if (!isBundlerESMBuild) {
  196. // hard coded dev/prod builds
  197. defines.__DEV__ = String(!isProductionBuild)
  198. }
  199. // allow inline overrides like
  200. //__RUNTIME_COMPILE__=true pnpm build runtime-core
  201. Object.keys(defines).forEach(key => {
  202. if (key in process.env) {
  203. const value = process.env[key]
  204. assert(typeof value === 'string')
  205. defines[key] = value
  206. }
  207. })
  208. return defines
  209. }
  210. // define is a bit strict and only allows literal json or identifiers
  211. // so we still need replace plugin in some cases
  212. function resolveReplace() {
  213. /** @type {Record<string, string>} */
  214. const replacements = { ...enumDefines }
  215. if (isBundlerESMBuild) {
  216. Object.assign(replacements, {
  217. // preserve to be handled by bundlers
  218. __DEV__: `!!(process.env.NODE_ENV !== 'production')`,
  219. })
  220. }
  221. // for compiler-sfc browser build inlined deps
  222. if (isBrowserESMBuild && name === 'compiler-sfc') {
  223. Object.assign(replacements, {
  224. 'process.env': '({})',
  225. 'process.platform': '""',
  226. 'process.stdout': 'null',
  227. })
  228. }
  229. if (Object.keys(replacements).length) {
  230. return [
  231. replacePlugin(replacements, {
  232. preventAssignment: true,
  233. }),
  234. ]
  235. } else {
  236. return []
  237. }
  238. }
  239. function resolveExternal() {
  240. const treeShakenDeps = [
  241. 'source-map-js',
  242. '@babel/parser',
  243. 'estree-walker',
  244. 'entities/lib/decode.js',
  245. ]
  246. // we are bundling forked consolidate.js in compiler-sfc which dynamically
  247. // requires a ton of template engines which should be ignored.
  248. /** @type {string[]} */
  249. let cjsIgnores = []
  250. if (
  251. pkg.name === '@vue/compiler-sfc' ||
  252. pkg.name === '@vue/compiler-sfc-canary'
  253. ) {
  254. cjsIgnores = [
  255. ...Object.keys(consolidatePkg.devDependencies),
  256. 'vm',
  257. 'crypto',
  258. 'react-dom/server',
  259. 'teacup/lib/express',
  260. 'arc-templates/dist/es5',
  261. 'then-pug',
  262. 'then-jade',
  263. ]
  264. }
  265. if (isGlobalBuild || isBrowserESMBuild || isCompatPackage || inlineDeps) {
  266. if (!packageOptions.enableNonBrowserBranches) {
  267. // normal browser builds - non-browser only imports are tree-shaken,
  268. // they are only listed here to suppress warnings.
  269. return treeShakenDeps
  270. } else {
  271. return cjsIgnores
  272. }
  273. } else {
  274. // Node / esm-bundler builds.
  275. // externalize all direct deps unless it's the compat build.
  276. return [
  277. ...Object.keys(pkg.dependencies || {}),
  278. ...Object.keys(pkg.peerDependencies || {}),
  279. // for @vue/compiler-sfc / server-renderer
  280. ...['path', 'url', 'stream'],
  281. // somehow these throw warnings for runtime-* package builds
  282. ...treeShakenDeps,
  283. ...cjsIgnores,
  284. ]
  285. }
  286. }
  287. function resolveNodePlugins() {
  288. const nodePlugins =
  289. (format === 'cjs' && Object.keys(pkg.devDependencies || {}).length) ||
  290. packageOptions.enableNonBrowserBranches
  291. ? [...(format === 'cjs' ? [] : [polyfillNode()])]
  292. : []
  293. return nodePlugins
  294. }
  295. return {
  296. input: resolve(entryFile),
  297. // Global and Browser ESM builds inlines everything so that they can be
  298. // used alone.
  299. external: resolveExternal(),
  300. transform: {
  301. define: resolveDefine(),
  302. target: isServerRenderer || isCJSBuild ? 'es2019' : 'es2016',
  303. },
  304. // IMPORTANT: the root tsconfig maps `vue` -> `runtime-with-vapor.ts` for TS usage.
  305. // For bundling we want `vue` to resolve to the normal entry to avoid pulling
  306. // runtime-vapor into non-vapor build graphs (e.g. server-renderer esm-browser).
  307. // this avoid MISSING_EXPORT errors for vapor-only exports.
  308. tsconfig: path.resolve(__dirname, '../tsconfig.rolldown.json'),
  309. platform:
  310. format === 'cjs' ? 'node' : isBundlerESMBuild ? 'neutral' : 'browser',
  311. resolve: {
  312. alias: entries,
  313. },
  314. plugins: [
  315. ...trimVaporExportsPlugin(format, pkg.name),
  316. ...(localDev ? [] : [enumPlugin]),
  317. ...resolveReplace(),
  318. ...resolveNodePlugins(),
  319. ...plugins,
  320. ],
  321. output,
  322. onwarn: (msg, warn) => {
  323. if (msg.code !== 'CIRCULAR_DEPENDENCY') {
  324. warn(msg)
  325. }
  326. },
  327. treeshake: {
  328. moduleSideEffects: false,
  329. },
  330. experimental: {
  331. nativeMagicString: true,
  332. },
  333. }
  334. }
  335. function createProductionConfig(/** @type {PackageFormat} */ format) {
  336. return createConfig(format, {
  337. file: resolve(`dist/${name}.${format}.prod.js`),
  338. format: outputConfigs[format].format,
  339. })
  340. }
  341. function createMinifiedConfig(/** @type {PackageFormat} */ format) {
  342. return createConfig(format, {
  343. file: String(outputConfigs[format].file).replace(/\.js$/, '.prod.js'),
  344. format: outputConfigs[format].format,
  345. minify: true,
  346. })
  347. }
  348. return packageConfigs
  349. }