create-rolldown-config.js 11 KB

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