rollup.config.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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' ||
  121. pkg.name === '@vue/compat-canary' ||
  122. pkg.name === '@vue-vapor/compat'
  123. const isCompatBuild = !!packageOptions.compat
  124. const isBrowserBuild =
  125. (isGlobalBuild || isBrowserESMBuild || isBundlerESMBuild) &&
  126. !packageOptions.enableNonBrowserBranches
  127. output.banner = `/**
  128. * ${pkg.name} v${masterVersion}
  129. * (c) 2018-present Yuxi (Evan) You and Vue contributors
  130. * @license MIT
  131. **/`
  132. output.exports = isCompatPackage ? 'auto' : 'named'
  133. if (isCJSBuild) {
  134. output.esModule = true
  135. }
  136. output.sourcemap = !!process.env.SOURCE_MAP
  137. output.externalLiveBindings = false
  138. // https://github.com/rollup/rollup/pull/5380
  139. output.reexportProtoFromExternal = false
  140. if (isGlobalBuild) {
  141. output.name = packageOptions.name
  142. }
  143. let entryFile = /\bruntime\b/.test(format) ? `runtime.ts` : `index.ts`
  144. // the compat build needs both default AND named exports. This will cause
  145. // Rollup to complain for non-ESM targets, so we use separate entries for
  146. // esm vs. non-esm builds.
  147. if (isCompatPackage && (isBrowserESMBuild || isBundlerESMBuild)) {
  148. entryFile = `esm-${entryFile}`
  149. }
  150. entryFile = 'src/' + entryFile
  151. return {
  152. input: resolve(entryFile),
  153. // Global and Browser ESM builds inlines everything so that they can be
  154. // used alone.
  155. external: resolveExternal(),
  156. plugins: [
  157. json({
  158. namedExports: false,
  159. }),
  160. alias({
  161. entries,
  162. }),
  163. enumPlugin,
  164. ...resolveReplace(),
  165. esbuild({
  166. tsconfig: path.resolve(__dirname, 'tsconfig.json'),
  167. sourceMap: output.sourcemap,
  168. minify: false,
  169. target: isServerRenderer || isCJSBuild ? 'es2019' : 'es2016',
  170. define: resolveDefine(),
  171. }),
  172. ...resolveNodePlugins(),
  173. ...plugins,
  174. ],
  175. output,
  176. onwarn(msg, warn) {
  177. if (msg.code !== 'CIRCULAR_DEPENDENCY') {
  178. warn(msg)
  179. }
  180. },
  181. treeshake: {
  182. moduleSideEffects: false,
  183. },
  184. }
  185. function resolveDefine() {
  186. /** @type {Record<string, string>} */
  187. const replacements = {
  188. __COMMIT__: `"${process.env.COMMIT}"`,
  189. __VERSION__: `"${masterVersion}"`,
  190. // this is only used during Vue's internal tests
  191. __TEST__: `false`,
  192. // If the build is expected to run directly in the browser (global / esm builds)
  193. __BROWSER__: String(isBrowserBuild),
  194. __GLOBAL__: String(isGlobalBuild),
  195. __ESM_BUNDLER__: String(isBundlerESMBuild),
  196. __ESM_BROWSER__: String(isBrowserESMBuild),
  197. // is targeting Node (SSR)?
  198. __CJS__: String(isCJSBuild),
  199. // need SSR-specific branches?
  200. __SSR__: String(!isGlobalBuild),
  201. __BENCHMARK__: process.env.BENCHMARK || 'false',
  202. // 2.x compat build
  203. __COMPAT__: String(isCompatBuild),
  204. // feature flags
  205. __FEATURE_SUSPENSE__: `true`,
  206. __FEATURE_OPTIONS_API__: isBundlerESMBuild
  207. ? `__VUE_OPTIONS_API__`
  208. : `true`,
  209. __FEATURE_PROD_DEVTOOLS__: isBundlerESMBuild
  210. ? `__VUE_PROD_DEVTOOLS__`
  211. : `false`,
  212. __FEATURE_PROD_HYDRATION_MISMATCH_DETAILS__: isBundlerESMBuild
  213. ? `__VUE_PROD_HYDRATION_MISMATCH_DETAILS__`
  214. : `false`,
  215. }
  216. if (!isBundlerESMBuild) {
  217. // hard coded dev/prod builds
  218. replacements.__DEV__ = String(!isProductionBuild)
  219. }
  220. // allow inline overrides like
  221. //__RUNTIME_COMPILE__=true pnpm build runtime-core
  222. Object.keys(replacements).forEach(key => {
  223. if (key in process.env) {
  224. const value = process.env[key]
  225. assert(typeof value === 'string')
  226. replacements[key] = value
  227. }
  228. })
  229. return replacements
  230. }
  231. // esbuild define is a bit strict and only allows literal json or identifiers
  232. // so we still need replace plugin in some cases
  233. function resolveReplace() {
  234. const replacements = { ...enumDefines }
  235. if (isProductionBuild && isBrowserBuild) {
  236. Object.assign(replacements, {
  237. 'context.onError(': `/*@__PURE__*/ context.onError(`,
  238. 'emitError(': `/*@__PURE__*/ emitError(`,
  239. 'createCompilerError(': `/*@__PURE__*/ createCompilerError(`,
  240. 'createDOMCompilerError(': `/*@__PURE__*/ createDOMCompilerError(`,
  241. })
  242. }
  243. if (isBundlerESMBuild) {
  244. Object.assign(replacements, {
  245. // preserve to be handled by bundlers
  246. __DEV__: `!!(process.env.NODE_ENV !== 'production')`,
  247. })
  248. }
  249. // for compiler-sfc browser build inlined deps
  250. if (isBrowserESMBuild) {
  251. Object.assign(replacements, {
  252. 'process.env': '({})',
  253. 'process.platform': '""',
  254. 'process.stdout': 'null',
  255. })
  256. }
  257. if (Object.keys(replacements).length) {
  258. return [replace({ values: replacements, preventAssignment: true })]
  259. } else {
  260. return []
  261. }
  262. }
  263. function resolveExternal() {
  264. const treeShakenDeps = [
  265. 'source-map-js',
  266. '@babel/parser',
  267. 'estree-walker',
  268. 'entities/lib/decode.js',
  269. ]
  270. if (isGlobalBuild || isBrowserESMBuild || isCompatPackage) {
  271. if (!packageOptions.enableNonBrowserBranches) {
  272. // normal browser builds - non-browser only imports are tree-shaken,
  273. // they are only listed here to suppress warnings.
  274. return treeShakenDeps
  275. }
  276. } else {
  277. // Node / esm-bundler builds.
  278. // externalize all direct deps unless it's the compat build.
  279. return [
  280. ...Object.keys(pkg.dependencies || {}),
  281. ...Object.keys(pkg.peerDependencies || {}),
  282. // for @vue/compiler-sfc / server-renderer
  283. ...['path', 'url', 'stream'],
  284. // somehow these throw warnings for runtime-* package builds
  285. ...treeShakenDeps,
  286. ]
  287. }
  288. }
  289. function resolveNodePlugins() {
  290. // we are bundling forked consolidate.js in compiler-sfc which dynamically
  291. // requires a ton of template engines which should be ignored.
  292. /** @type {ReadonlyArray<string>} */
  293. let cjsIgnores = []
  294. if (
  295. pkg.name === '@vue/compiler-sfc' ||
  296. pkg.name === '@vue/compiler-sfc-canary' ||
  297. pkg.name === '@vue-vapor/compiler-sfc'
  298. ) {
  299. cjsIgnores = [
  300. ...Object.keys(consolidatePkg.devDependencies),
  301. 'vm',
  302. 'crypto',
  303. 'react-dom/server',
  304. 'teacup/lib/express',
  305. 'arc-templates/dist/es5',
  306. 'then-pug',
  307. 'then-jade',
  308. ]
  309. }
  310. const nodePlugins =
  311. (format === 'cjs' && Object.keys(pkg.devDependencies || {}).length) ||
  312. packageOptions.enableNonBrowserBranches
  313. ? [
  314. commonJS({
  315. sourceMap: false,
  316. ignore: cjsIgnores,
  317. }),
  318. ...(format === 'cjs' ? [] : [polyfillNode()]),
  319. nodeResolve(),
  320. ]
  321. : []
  322. return nodePlugins
  323. }
  324. }
  325. function createProductionConfig(/** @type {PackageFormat} */ format) {
  326. return createConfig(format, {
  327. ...outputConfigs[format],
  328. file: resolve(`dist/${name}.${format}.prod.js`),
  329. })
  330. }
  331. function createMinifiedConfig(/** @type {PackageFormat} */ format) {
  332. return createConfig(
  333. format,
  334. {
  335. ...outputConfigs[format],
  336. file: outputConfigs[format].file.replace(/\.js$/, '.prod.js'),
  337. },
  338. [
  339. {
  340. name: 'swc-minify',
  341. async renderChunk(
  342. contents,
  343. _,
  344. { format, sourcemap, sourcemapExcludeSources },
  345. ) {
  346. const { code, map } = await minifySwc(contents, {
  347. module: format === 'es',
  348. compress: {
  349. ecma: 2016,
  350. pure_getters: true,
  351. },
  352. safari10: true,
  353. mangle: true,
  354. sourceMap: !!sourcemap,
  355. inlineSourcesContent: !sourcemapExcludeSources,
  356. })
  357. return { code, map: map || null }
  358. },
  359. },
  360. ],
  361. )
  362. }