rollup.config.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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 = pkg.name === '@vue/compat'
  94. const isCompatBuild = !!packageOptions.compat
  95. const isBrowserBuild =
  96. (isGlobalBuild || isBrowserESMBuild || isBundlerESMBuild) &&
  97. !packageOptions.enableNonBrowserBranches
  98. output.exports = isCompatPackage ? 'auto' : 'named'
  99. if (isNodeBuild) {
  100. output.esModule = true
  101. }
  102. output.sourcemap = !!process.env.SOURCE_MAP
  103. output.externalLiveBindings = false
  104. if (isGlobalBuild) {
  105. output.name = packageOptions.name
  106. }
  107. let entryFile = /runtime$/.test(format) ? `src/runtime.ts` : `src/index.ts`
  108. // the compat build needs both default AND named exports. This will cause
  109. // Rollup to complain for non-ESM targets, so we use separate entries for
  110. // esm vs. non-esm builds.
  111. if (isCompatPackage && (isBrowserESMBuild || isBundlerESMBuild)) {
  112. entryFile = /runtime$/.test(format)
  113. ? `src/esm-runtime.ts`
  114. : `src/esm-index.ts`
  115. }
  116. function resolveDefine() {
  117. const replacements = {
  118. __COMMIT__: `"${process.env.COMMIT}"`,
  119. __VERSION__: `"${masterVersion}"`,
  120. // this is only used during Vue's internal tests
  121. __TEST__: `false`,
  122. // If the build is expected to run directly in the browser (global / esm builds)
  123. __BROWSER__: String(isBrowserBuild),
  124. __GLOBAL__: String(isGlobalBuild),
  125. __ESM_BUNDLER__: String(isBundlerESMBuild),
  126. __ESM_BROWSER__: String(isBrowserESMBuild),
  127. // is targeting Node (SSR)?
  128. __NODE_JS__: String(isNodeBuild),
  129. // need SSR-specific branches?
  130. __SSR__: String(isNodeBuild || isBundlerESMBuild || isServerRenderer),
  131. // 2.x compat build
  132. __COMPAT__: String(isCompatBuild),
  133. // feature flags
  134. __FEATURE_SUSPENSE__: `true`,
  135. __FEATURE_OPTIONS_API__: isBundlerESMBuild
  136. ? `__VUE_OPTIONS_API__`
  137. : `true`,
  138. __FEATURE_PROD_DEVTOOLS__: isBundlerESMBuild
  139. ? `__VUE_PROD_DEVTOOLS__`
  140. : `false`
  141. }
  142. if (!isBundlerESMBuild) {
  143. // hard coded dev/prod builds
  144. // @ts-ignore
  145. replacements.__DEV__ = String(!isProductionBuild)
  146. }
  147. // allow inline overrides like
  148. //__RUNTIME_COMPILE__=true pnpm build runtime-core
  149. Object.keys(replacements).forEach(key => {
  150. if (key in process.env) {
  151. replacements[key] = process.env[key]
  152. }
  153. })
  154. return replacements
  155. }
  156. // esbuild define is a bit strict and only allows literal json or identifiers
  157. // so we still need replace plugin in some cases
  158. function resolveReplace() {
  159. const replacements = { ...enumDefines }
  160. if (isProductionBuild && isBrowserBuild) {
  161. Object.assign(replacements, {
  162. 'context.onError(': `/*#__PURE__*/ context.onError(`,
  163. 'emitError(': `/*#__PURE__*/ emitError(`,
  164. 'createCompilerError(': `/*#__PURE__*/ createCompilerError(`,
  165. 'createDOMCompilerError(': `/*#__PURE__*/ createDOMCompilerError(`
  166. })
  167. }
  168. if (isBundlerESMBuild) {
  169. Object.assign(replacements, {
  170. // preserve to be handled by bundlers
  171. __DEV__: `process.env.NODE_ENV !== 'production'`
  172. })
  173. }
  174. // for compiler-sfc browser build inlined deps
  175. if (isBrowserESMBuild) {
  176. Object.assign(replacements, {
  177. 'process.env': '({})',
  178. 'process.platform': '""',
  179. 'process.stdout': 'null'
  180. })
  181. }
  182. if (Object.keys(replacements).length) {
  183. // @ts-ignore
  184. return [replace({ values: replacements, preventAssignment: true })]
  185. } else {
  186. return []
  187. }
  188. }
  189. function resolveExternal() {
  190. const treeShakenDeps = ['source-map', '@babel/parser', 'estree-walker']
  191. if (isGlobalBuild || isBrowserESMBuild || isCompatPackage) {
  192. if (!packageOptions.enableNonBrowserBranches) {
  193. // normal browser builds - non-browser only imports are tree-shaken,
  194. // they are only listed here to suppress warnings.
  195. return treeShakenDeps
  196. }
  197. } else {
  198. // Node / esm-bundler builds.
  199. // externalize all direct deps unless it's the compat build.
  200. return [
  201. ...Object.keys(pkg.dependencies || {}),
  202. ...Object.keys(pkg.peerDependencies || {}),
  203. // for @vue/compiler-sfc / server-renderer
  204. ...['path', 'url', 'stream'],
  205. // somehow these throw warnings for runtime-* package builds
  206. ...treeShakenDeps
  207. ]
  208. }
  209. }
  210. function resolveNodePlugins() {
  211. // we are bundling forked consolidate.js in compiler-sfc which dynamically
  212. // requires a ton of template engines which should be ignored.
  213. let cjsIgnores = []
  214. if (pkg.name === '@vue/compiler-sfc') {
  215. cjsIgnores = [
  216. ...Object.keys(consolidatePkg.devDependencies),
  217. 'vm',
  218. 'crypto',
  219. 'react-dom/server',
  220. 'teacup/lib/express',
  221. 'arc-templates/dist/es5',
  222. 'then-pug',
  223. 'then-jade'
  224. ]
  225. }
  226. const nodePlugins =
  227. (format === 'cjs' && Object.keys(pkg.devDependencies || {}).length) ||
  228. packageOptions.enableNonBrowserBranches
  229. ? [
  230. commonJS({
  231. sourceMap: false,
  232. ignore: cjsIgnores
  233. }),
  234. ...(format === 'cjs' ? [] : [polyfillNode()]),
  235. nodeResolve()
  236. ]
  237. : []
  238. if (format === 'cjs') {
  239. nodePlugins.push(cjsReExportsPatchPlugin())
  240. }
  241. return nodePlugins
  242. }
  243. return {
  244. input: resolve(entryFile),
  245. // Global and Browser ESM builds inlines everything so that they can be
  246. // used alone.
  247. external: resolveExternal(),
  248. plugins: [
  249. json({
  250. namedExports: false
  251. }),
  252. alias({
  253. entries
  254. }),
  255. enumPlugin,
  256. ...resolveReplace(),
  257. esbuild({
  258. tsconfig: path.resolve(__dirname, 'tsconfig.json'),
  259. sourceMap: output.sourcemap,
  260. minify: false,
  261. target: isServerRenderer || isNodeBuild ? 'es2019' : 'es2015',
  262. define: resolveDefine()
  263. }),
  264. ...resolveNodePlugins(),
  265. ...plugins
  266. ],
  267. output,
  268. onwarn: (msg, warn) => {
  269. if (!/Circular/.test(msg)) {
  270. warn(msg)
  271. }
  272. },
  273. treeshake: {
  274. moduleSideEffects: false
  275. }
  276. }
  277. }
  278. function createProductionConfig(format) {
  279. return createConfig(format, {
  280. file: resolve(`dist/${name}.${format}.prod.js`),
  281. format: outputConfigs[format].format
  282. })
  283. }
  284. function createMinifiedConfig(format) {
  285. return createConfig(
  286. format,
  287. {
  288. file: outputConfigs[format].file.replace(/\.js$/, '.prod.js'),
  289. format: outputConfigs[format].format
  290. },
  291. [
  292. terser({
  293. module: /^esm/.test(format),
  294. compress: {
  295. ecma: 2015,
  296. pure_getters: true
  297. },
  298. safari10: true
  299. })
  300. ]
  301. )
  302. }
  303. // temporary patch for https://github.com/nodejs/cjs-module-lexer/issues/79
  304. //
  305. // When importing a cjs module from esm, Node.js uses cjs-module-lexer to
  306. // detect * re-exports from other packages. However, the detection logic is
  307. // fragile and breaks when Rollup generates different code for the re-exports.
  308. // We were locked on an old version of Rollup because of this.
  309. //
  310. // The latest versions of Node ships an updated version of cjs-module-lexer that
  311. // has fixed https://github.com/nodejs/cjs-module-lexer/issues/38, however we
  312. // still need to support older versions of Node that does not have the latest
  313. // version of cjs-module-lexer (Node < 14.18)
  314. //
  315. // At the same time, we want to upgrade to Rollup 3 so we are not forever locked
  316. // on an old version of Rollup.
  317. //
  318. // What this patch does:
  319. // 1. Rewrite the for...in loop to Object.keys() so cjs-module-lexer can find it
  320. // The for...in loop is only used when output.externalLiveBindings is set to
  321. // false, and we do want to set it to false to avoid perf costs during SSR.
  322. // 2. Also remove exports.hasOwnProperty check, which breaks the detection in
  323. // Node.js versions that
  324. //
  325. // TODO in the future, we should no longer rely on this if we inline all deps
  326. // in the main `vue` package.
  327. function cjsReExportsPatchPlugin() {
  328. const matcher =
  329. /for \(var k in (\w+)\) {(\s+if \(k !== 'default') && !exports.hasOwnProperty\(k\)(\) exports\[k\] = (?:\w+)\[k\];\s+)}/
  330. return {
  331. name: 'patch-cjs-re-exports',
  332. renderChunk(code, _, options) {
  333. if (matcher.test(code)) {
  334. return code.replace(matcher, (_, r1, r2, r3) => {
  335. return `Object.keys(${r1}).forEach(function(k) {${r2}${r3}});`
  336. })
  337. } else if (options.file.endsWith('packages/vue/dist/vue.cjs.js')) {
  338. // make sure we don't accidentally miss the rewrite in case Rollup
  339. // changes the output again.
  340. throw new Error('cjs build re-exports rewrite failed.')
  341. }
  342. }
  343. }
  344. }