rollup.config.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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 { 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(pico.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 = [
  192. 'source-map-js',
  193. '@babel/parser',
  194. 'estree-walker',
  195. 'entities/lib/decode.js'
  196. ]
  197. if (isGlobalBuild || isBrowserESMBuild || isCompatPackage) {
  198. if (!packageOptions.enableNonBrowserBranches) {
  199. // normal browser builds - non-browser only imports are tree-shaken,
  200. // they are only listed here to suppress warnings.
  201. return treeShakenDeps
  202. }
  203. } else {
  204. // Node / esm-bundler builds.
  205. // externalize all direct deps unless it's the compat build.
  206. return [
  207. ...Object.keys(pkg.dependencies || {}),
  208. ...Object.keys(pkg.peerDependencies || {}),
  209. // for @vue/compiler-sfc / server-renderer
  210. ...['path', 'url', 'stream'],
  211. // somehow these throw warnings for runtime-* package builds
  212. ...treeShakenDeps
  213. ]
  214. }
  215. }
  216. function resolveNodePlugins() {
  217. // we are bundling forked consolidate.js in compiler-sfc which dynamically
  218. // requires a ton of template engines which should be ignored.
  219. let cjsIgnores = []
  220. if (
  221. pkg.name === '@vue/compiler-sfc' ||
  222. pkg.name === '@vue/compiler-sfc-canary'
  223. ) {
  224. cjsIgnores = [
  225. ...Object.keys(consolidatePkg.devDependencies),
  226. 'vm',
  227. 'crypto',
  228. 'react-dom/server',
  229. 'teacup/lib/express',
  230. 'arc-templates/dist/es5',
  231. 'then-pug',
  232. 'then-jade'
  233. ]
  234. }
  235. const nodePlugins =
  236. (format === 'cjs' && Object.keys(pkg.devDependencies || {}).length) ||
  237. packageOptions.enableNonBrowserBranches
  238. ? [
  239. commonJS({
  240. sourceMap: false,
  241. ignore: cjsIgnores
  242. }),
  243. ...(format === 'cjs' ? [] : [polyfillNode()]),
  244. nodeResolve()
  245. ]
  246. : []
  247. return nodePlugins
  248. }
  249. return {
  250. input: resolve(entryFile),
  251. // Global and Browser ESM builds inlines everything so that they can be
  252. // used alone.
  253. external: resolveExternal(),
  254. plugins: [
  255. json({
  256. namedExports: false
  257. }),
  258. alias({
  259. entries
  260. }),
  261. enumPlugin,
  262. ...resolveReplace(),
  263. esbuild({
  264. tsconfig: path.resolve(__dirname, 'tsconfig.json'),
  265. sourceMap: output.sourcemap,
  266. minify: false,
  267. target: isServerRenderer || isNodeBuild ? 'es2019' : 'es2015',
  268. define: resolveDefine()
  269. }),
  270. ...resolveNodePlugins(),
  271. ...plugins
  272. ],
  273. output,
  274. onwarn: (msg, warn) => {
  275. if (!/Circular/.test(msg)) {
  276. warn(msg)
  277. }
  278. },
  279. treeshake: {
  280. moduleSideEffects: false
  281. }
  282. }
  283. }
  284. function createProductionConfig(format) {
  285. return createConfig(format, {
  286. file: resolve(`dist/${name}.${format}.prod.js`),
  287. format: outputConfigs[format].format
  288. })
  289. }
  290. function createMinifiedConfig(format) {
  291. return createConfig(
  292. format,
  293. {
  294. file: outputConfigs[format].file.replace(/\.js$/, '.prod.js'),
  295. format: outputConfigs[format].format
  296. },
  297. [
  298. terser({
  299. module: /^esm/.test(format),
  300. compress: {
  301. ecma: 2015,
  302. pure_getters: true
  303. },
  304. safari10: true
  305. })
  306. ]
  307. )
  308. }