rollup.config.js 9.8 KB

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