rollup.config.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. // @ts-check
  2. import assert from 'node:assert/strict'
  3. import { createRequire } from 'node:module'
  4. import { fileURLToPath } from 'node:url'
  5. import fs from 'node:fs'
  6. import path from 'node:path'
  7. import replace from '@rollup/plugin-replace'
  8. import json from '@rollup/plugin-json'
  9. import pico from 'picocolors'
  10. import commonJS from '@rollup/plugin-commonjs'
  11. import polyfillNode from 'rollup-plugin-polyfill-node'
  12. import { nodeResolve } from '@rollup/plugin-node-resolve'
  13. import esbuild from 'rollup-plugin-esbuild'
  14. import alias from '@rollup/plugin-alias'
  15. import { entries } from './scripts/aliases.js'
  16. import { inlineEnums } from './scripts/inline-enums.js'
  17. import { minify as minifySwc } from '@swc/core'
  18. /**
  19. * @template T
  20. * @template {keyof T} K
  21. * @typedef { Omit<T, K> & Required<Pick<T, K>> } MarkRequired
  22. */
  23. /** @typedef {'cjs' | 'esm-bundler' | 'global' | 'global-runtime' | 'esm-browser' | 'esm-bundler-runtime' | 'esm-browser-runtime'} PackageFormat */
  24. /** @typedef {MarkRequired<import('rollup').OutputOptions, 'file' | 'format'>} OutputOptions */
  25. if (!process.env.TARGET) {
  26. throw new Error('TARGET package must be specified via --environment flag.')
  27. }
  28. const require = createRequire(import.meta.url)
  29. const __dirname = fileURLToPath(new URL('.', import.meta.url))
  30. const masterVersion = require('./package.json').version
  31. const consolidatePkg = require('@vue/consolidate/package.json')
  32. const privatePackages = fs.readdirSync('packages-private')
  33. const pkgBase = privatePackages.includes(process.env.TARGET)
  34. ? `packages-private`
  35. : `packages`
  36. const packagesDir = path.resolve(__dirname, pkgBase)
  37. const packageDir = path.resolve(packagesDir, process.env.TARGET)
  38. const resolve = (/** @type {string} */ p) => path.resolve(packageDir, p)
  39. const pkg = require(resolve(`package.json`))
  40. const packageOptions = pkg.buildOptions || {}
  41. const name = packageOptions.filename || path.basename(packageDir)
  42. const [enumPlugin, enumDefines] = inlineEnums()
  43. /** @type {Record<PackageFormat, OutputOptions>} */
  44. const outputConfigs = {
  45. 'esm-bundler': {
  46. file: resolve(`dist/${name}.esm-bundler.js`),
  47. format: 'es',
  48. },
  49. 'esm-browser': {
  50. file: resolve(`dist/${name}.esm-browser.js`),
  51. format: 'es',
  52. },
  53. cjs: {
  54. file: resolve(`dist/${name}.cjs.js`),
  55. format: 'cjs',
  56. },
  57. global: {
  58. file: resolve(`dist/${name}.global.js`),
  59. format: 'iife',
  60. },
  61. // runtime-only builds, for main "vue" package only
  62. 'esm-bundler-runtime': {
  63. file: resolve(`dist/${name}.runtime.esm-bundler.js`),
  64. format: 'es',
  65. },
  66. 'esm-browser-runtime': {
  67. file: resolve(`dist/${name}.runtime.esm-browser.js`),
  68. format: 'es',
  69. },
  70. 'global-runtime': {
  71. file: resolve(`dist/${name}.runtime.global.js`),
  72. format: 'iife',
  73. },
  74. }
  75. /** @type {ReadonlyArray<PackageFormat>} */
  76. const defaultFormats = ['esm-bundler', 'cjs']
  77. /** @type {ReadonlyArray<PackageFormat>} */
  78. const inlineFormats = /** @type {any} */ (
  79. process.env.FORMATS && process.env.FORMATS.split(',')
  80. )
  81. /** @type {ReadonlyArray<PackageFormat>} */
  82. const packageFormats = inlineFormats || packageOptions.formats || defaultFormats
  83. const packageConfigs = process.env.PROD_ONLY
  84. ? []
  85. : packageFormats.map(format => createConfig(format, outputConfigs[format]))
  86. if (process.env.NODE_ENV === 'production') {
  87. packageFormats.forEach(format => {
  88. if (packageOptions.prod === false) {
  89. return
  90. }
  91. if (format === 'cjs') {
  92. packageConfigs.push(createProductionConfig(format))
  93. }
  94. if (/^(global|esm-browser)(-runtime)?/.test(format)) {
  95. packageConfigs.push(createMinifiedConfig(format))
  96. }
  97. })
  98. }
  99. export default packageConfigs
  100. /**
  101. *
  102. * @param {PackageFormat} format
  103. * @param {OutputOptions} output
  104. * @param {ReadonlyArray<import('rollup').Plugin>} plugins
  105. * @returns {import('rollup').RollupOptions}
  106. */
  107. function createConfig(format, output, plugins = []) {
  108. if (!output) {
  109. console.log(pico.yellow(`invalid format: "${format}"`))
  110. process.exit(1)
  111. }
  112. const isProductionBuild =
  113. process.env.__DEV__ === 'false' || /\.prod\.js$/.test(output.file)
  114. const isBundlerESMBuild = /esm-bundler/.test(format)
  115. const isBrowserESMBuild = /esm-browser/.test(format)
  116. const isServerRenderer = name === 'server-renderer'
  117. const isCJSBuild = format === 'cjs'
  118. const isGlobalBuild = /global/.test(format)
  119. const isCompatPackage =
  120. pkg.name === '@vue/compat' || pkg.name === '@vue/compat-canary'
  121. const isCompatBuild = !!packageOptions.compat
  122. const isBrowserBuild =
  123. (isGlobalBuild || isBrowserESMBuild || isBundlerESMBuild) &&
  124. !packageOptions.enableNonBrowserBranches
  125. output.banner = `/**
  126. * ${pkg.name} v${masterVersion}
  127. * (c) 2018-present Yuxi (Evan) You and Vue contributors
  128. * @license MIT
  129. **/`
  130. output.exports = isCompatPackage ? 'auto' : 'named'
  131. if (isCJSBuild) {
  132. output.esModule = true
  133. }
  134. output.sourcemap = !!process.env.SOURCE_MAP
  135. output.externalLiveBindings = false
  136. // https://github.com/rollup/rollup/pull/5380
  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 replacements = {
  153. __COMMIT__: `"${process.env.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(!isGlobalBuild),
  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. replacements.__DEV__ = String(!isProductionBuild)
  183. }
  184. // allow inline overrides like
  185. //__RUNTIME_COMPILE__=true pnpm build runtime-core
  186. Object.keys(replacements).forEach(key => {
  187. if (key in process.env) {
  188. const value = process.env[key]
  189. assert(typeof value === 'string')
  190. replacements[key] = value
  191. }
  192. })
  193. return replacements
  194. }
  195. // esbuild 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. const replacements = { ...enumDefines }
  199. if (isProductionBuild && isBrowserBuild) {
  200. Object.assign(replacements, {
  201. 'context.onError(': `/*#__PURE__*/ context.onError(`,
  202. 'emitError(': `/*#__PURE__*/ emitError(`,
  203. 'createCompilerError(': `/*#__PURE__*/ createCompilerError(`,
  204. 'createDOMCompilerError(': `/*#__PURE__*/ createDOMCompilerError(`,
  205. })
  206. }
  207. if (isBundlerESMBuild) {
  208. Object.assign(replacements, {
  209. // preserve to be handled by bundlers
  210. __DEV__: `!!(process.env.NODE_ENV !== 'production')`,
  211. })
  212. }
  213. // for compiler-sfc browser build inlined deps
  214. if (isBrowserESMBuild) {
  215. Object.assign(replacements, {
  216. 'process.env': '({})',
  217. 'process.platform': '""',
  218. 'process.stdout': 'null',
  219. })
  220. }
  221. if (Object.keys(replacements).length) {
  222. return [replace({ values: replacements, preventAssignment: true })]
  223. } else {
  224. return []
  225. }
  226. }
  227. function resolveExternal() {
  228. const treeShakenDeps = [
  229. 'source-map-js',
  230. '@babel/parser',
  231. 'estree-walker',
  232. 'entities/lib/decode.js',
  233. ]
  234. if (isGlobalBuild || isBrowserESMBuild || isCompatPackage) {
  235. if (!packageOptions.enableNonBrowserBranches) {
  236. // normal browser builds - non-browser only imports are tree-shaken,
  237. // they are only listed here to suppress warnings.
  238. return treeShakenDeps
  239. }
  240. } else {
  241. // Node / esm-bundler builds.
  242. // externalize all direct deps unless it's the compat build.
  243. return [
  244. ...Object.keys(pkg.dependencies || {}),
  245. ...Object.keys(pkg.peerDependencies || {}),
  246. // for @vue/compiler-sfc / server-renderer
  247. ...['path', 'url', 'stream'],
  248. // somehow these throw warnings for runtime-* package builds
  249. ...treeShakenDeps,
  250. ]
  251. }
  252. }
  253. function resolveNodePlugins() {
  254. // we are bundling forked consolidate.js in compiler-sfc which dynamically
  255. // requires a ton of template engines which should be ignored.
  256. /** @type {ReadonlyArray<string>} */
  257. let cjsIgnores = []
  258. if (
  259. pkg.name === '@vue/compiler-sfc' ||
  260. pkg.name === '@vue/compiler-sfc-canary'
  261. ) {
  262. cjsIgnores = [
  263. ...Object.keys(consolidatePkg.devDependencies),
  264. 'vm',
  265. 'crypto',
  266. 'react-dom/server',
  267. 'teacup/lib/express',
  268. 'arc-templates/dist/es5',
  269. 'then-pug',
  270. 'then-jade',
  271. ]
  272. }
  273. const nodePlugins =
  274. (format === 'cjs' && Object.keys(pkg.devDependencies || {}).length) ||
  275. packageOptions.enableNonBrowserBranches
  276. ? [
  277. commonJS({
  278. sourceMap: false,
  279. ignore: cjsIgnores,
  280. }),
  281. ...(format === 'cjs' ? [] : [polyfillNode()]),
  282. nodeResolve(),
  283. ]
  284. : []
  285. return nodePlugins
  286. }
  287. return {
  288. input: resolve(entryFile),
  289. // Global and Browser ESM builds inlines everything so that they can be
  290. // used alone.
  291. external: resolveExternal(),
  292. plugins: [
  293. json({
  294. namedExports: false,
  295. }),
  296. alias({
  297. entries,
  298. }),
  299. enumPlugin,
  300. ...resolveReplace(),
  301. esbuild({
  302. tsconfig: path.resolve(__dirname, 'tsconfig.json'),
  303. sourceMap: output.sourcemap,
  304. minify: false,
  305. target: isServerRenderer || isCJSBuild ? 'es2019' : 'es2016',
  306. define: resolveDefine(),
  307. }),
  308. ...resolveNodePlugins(),
  309. ...plugins,
  310. ],
  311. output,
  312. onwarn: (msg, warn) => {
  313. if (msg.code !== 'CIRCULAR_DEPENDENCY') {
  314. warn(msg)
  315. }
  316. },
  317. treeshake: {
  318. moduleSideEffects: false,
  319. },
  320. }
  321. }
  322. function createProductionConfig(/** @type {PackageFormat} */ format) {
  323. return createConfig(format, {
  324. file: resolve(`dist/${name}.${format}.prod.js`),
  325. format: outputConfigs[format].format,
  326. })
  327. }
  328. function createMinifiedConfig(/** @type {PackageFormat} */ format) {
  329. return createConfig(
  330. format,
  331. {
  332. file: outputConfigs[format].file.replace(/\.js$/, '.prod.js'),
  333. format: outputConfigs[format].format,
  334. },
  335. [
  336. {
  337. name: 'swc-minify',
  338. async renderChunk(
  339. contents,
  340. _,
  341. { format, sourcemap, sourcemapExcludeSources },
  342. ) {
  343. const { code, map } = await minifySwc(contents, {
  344. module: format === 'es',
  345. compress: {
  346. ecma: 2016,
  347. pure_getters: true,
  348. },
  349. safari10: true,
  350. mangle: true,
  351. sourceMap: !!sourcemap,
  352. inlineSourcesContent: !sourcemapExcludeSources,
  353. })
  354. return { code, map: map || null }
  355. },
  356. },
  357. ],
  358. )
  359. }