rollup.config.js 11 KB

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