rollup.config.js 12 KB

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