rollup.config.js 12 KB

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