rollup.config.js 12 KB

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