rollup.config.js 11 KB

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