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' | 'esm-browser-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. 'esm-browser-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 (
  107. format === 'esm-browser-vapor' ||
  108. /^(global|esm-browser)(-runtime)?/.test(format)
  109. ) {
  110. packageConfigs.push(createMinifiedConfig(format))
  111. }
  112. })
  113. }
  114. export default packageConfigs
  115. /**
  116. *
  117. * @param {PackageFormat} format
  118. * @param {OutputOptions} output
  119. * @param {ReadonlyArray<import('rollup').Plugin>} plugins
  120. * @returns {import('rollup').RollupOptions}
  121. */
  122. function createConfig(format, output, plugins = []) {
  123. if (!output) {
  124. console.log(pico.yellow(`invalid format: "${format}"`))
  125. process.exit(1)
  126. }
  127. const isProductionBuild =
  128. process.env.__DEV__ === 'false' || /\.prod\.js$/.test(output.file)
  129. const isBundlerESMBuild = /esm-bundler/.test(format)
  130. const isBrowserESMBuild = /esm-browser/.test(format)
  131. const isServerRenderer = name === 'server-renderer'
  132. const isCJSBuild = format === 'cjs'
  133. const isGlobalBuild = /global/.test(format)
  134. const isCompatPackage = pkg.name === '@vue/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 = 'index.ts'
  152. if (pkg.name === 'vue') {
  153. if (format === 'esm-browser-vapor' || format === 'esm-bundler-runtime') {
  154. entryFile = 'runtime-with-vapor.ts'
  155. } else if (format === 'esm-bundler') {
  156. entryFile = 'index-with-vapor.ts'
  157. } else if (format.includes('runtime')) {
  158. entryFile = 'runtime.ts'
  159. }
  160. }
  161. // the compat build needs both default AND named exports. This will cause
  162. // Rollup to complain for non-ESM targets, so we use separate entries for
  163. // esm vs. non-esm builds.
  164. if (isCompatPackage && (isBrowserESMBuild || isBundlerESMBuild)) {
  165. entryFile = `esm-${entryFile}`
  166. }
  167. entryFile = 'src/' + entryFile
  168. return {
  169. input: resolve(entryFile),
  170. // Global and Browser ESM builds inlines everything so that they can be
  171. // used alone.
  172. external: resolveExternal(),
  173. plugins: [
  174. ...trimVaporExportsPlugin(format, pkg.name),
  175. json({
  176. namedExports: false,
  177. }),
  178. alias({
  179. entries,
  180. }),
  181. enumPlugin,
  182. ...resolveReplace(),
  183. esbuild({
  184. tsconfig: path.resolve(__dirname, 'tsconfig.json'),
  185. sourceMap: output.sourcemap,
  186. minify: false,
  187. target: isServerRenderer || isCJSBuild ? 'es2019' : 'es2016',
  188. define: resolveDefine(),
  189. }),
  190. ...resolveNodePlugins(),
  191. ...plugins,
  192. ],
  193. output,
  194. onwarn(msg, warn) {
  195. if (msg.code !== 'CIRCULAR_DEPENDENCY') {
  196. warn(msg)
  197. }
  198. },
  199. treeshake: {
  200. moduleSideEffects: false,
  201. },
  202. }
  203. function resolveDefine() {
  204. /** @type {Record<string, string>} */
  205. const replacements = {
  206. __COMMIT__: `"${process.env.COMMIT}"`,
  207. __VERSION__: `"${masterVersion}"`,
  208. // this is only used during Vue's internal tests
  209. __TEST__: `false`,
  210. // If the build is expected to run directly in the browser (global / esm builds)
  211. __BROWSER__: String(isBrowserBuild),
  212. __GLOBAL__: String(isGlobalBuild),
  213. __ESM_BUNDLER__: String(isBundlerESMBuild),
  214. __ESM_BROWSER__: String(isBrowserESMBuild),
  215. // is targeting Node (SSR)?
  216. __CJS__: String(isCJSBuild),
  217. // need SSR-specific branches?
  218. __SSR__: String(!isGlobalBuild),
  219. __BENCHMARK__: process.env.BENCHMARK || 'false',
  220. // 2.x compat build
  221. __COMPAT__: String(isCompatBuild),
  222. // feature flags
  223. __FEATURE_SUSPENSE__: `true`,
  224. __FEATURE_OPTIONS_API__: isBundlerESMBuild
  225. ? `__VUE_OPTIONS_API__`
  226. : `true`,
  227. __FEATURE_PROD_DEVTOOLS__: isBundlerESMBuild
  228. ? `__VUE_PROD_DEVTOOLS__`
  229. : `false`,
  230. __FEATURE_PROD_HYDRATION_MISMATCH_DETAILS__: isBundlerESMBuild
  231. ? `__VUE_PROD_HYDRATION_MISMATCH_DETAILS__`
  232. : `false`,
  233. }
  234. if (!isBundlerESMBuild) {
  235. // hard coded dev/prod builds
  236. replacements.__DEV__ = String(!isProductionBuild)
  237. }
  238. // allow inline overrides like
  239. //__RUNTIME_COMPILE__=true pnpm build runtime-core
  240. Object.keys(replacements).forEach(key => {
  241. if (key in process.env) {
  242. const value = process.env[key]
  243. assert(typeof value === 'string')
  244. replacements[key] = value
  245. }
  246. })
  247. return replacements
  248. }
  249. // esbuild define is a bit strict and only allows literal json or identifiers
  250. // so we still need replace plugin in some cases
  251. function resolveReplace() {
  252. const replacements = { ...enumDefines }
  253. if (isProductionBuild && isBrowserBuild) {
  254. Object.assign(replacements, {
  255. 'context.onError(': `/*@__PURE__*/ context.onError(`,
  256. 'emitError(': `/*@__PURE__*/ emitError(`,
  257. 'createCompilerError(': `/*@__PURE__*/ createCompilerError(`,
  258. 'createDOMCompilerError(': `/*@__PURE__*/ createDOMCompilerError(`,
  259. })
  260. }
  261. if (isBundlerESMBuild) {
  262. Object.assign(replacements, {
  263. // preserve to be handled by bundlers
  264. __DEV__: `!!(process.env.NODE_ENV !== 'production')`,
  265. })
  266. }
  267. // for compiler-sfc browser build inlined deps
  268. if (isBrowserESMBuild) {
  269. Object.assign(replacements, {
  270. 'process.env': '({})',
  271. 'process.platform': '""',
  272. 'process.stdout': 'null',
  273. })
  274. }
  275. if (Object.keys(replacements).length) {
  276. return [replace({ values: replacements, preventAssignment: true })]
  277. } else {
  278. return []
  279. }
  280. }
  281. function resolveExternal() {
  282. const treeShakenDeps = [
  283. 'source-map-js',
  284. '@babel/parser',
  285. '@babel/types',
  286. 'estree-walker',
  287. 'entities/decode',
  288. ]
  289. if (isGlobalBuild || isBrowserESMBuild || isCompatPackage) {
  290. if (!packageOptions.enableNonBrowserBranches) {
  291. // normal browser builds - non-browser only imports are tree-shaken,
  292. // they are only listed here to suppress warnings.
  293. return treeShakenDeps
  294. }
  295. } else {
  296. // Node / esm-bundler builds.
  297. // externalize all direct deps unless it's the compat build.
  298. return [
  299. ...Object.keys(pkg.dependencies || {}),
  300. ...Object.keys(pkg.peerDependencies || {}),
  301. // for @vue/compiler-sfc / server-renderer
  302. ...['path', 'url', 'stream'],
  303. // somehow these throw warnings for runtime-* package builds
  304. ...treeShakenDeps,
  305. ]
  306. }
  307. }
  308. function resolveNodePlugins() {
  309. // we are bundling forked consolidate.js in compiler-sfc which dynamically
  310. // requires a ton of template engines which should be ignored.
  311. /** @type {ReadonlyArray<string>} */
  312. let cjsIgnores = []
  313. if (pkg.name === '@vue/compiler-sfc') {
  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. }