rollup.config.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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', '@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. if (format === 'cjs') {
  243. nodePlugins.push(cjsReExportsPatchPlugin())
  244. }
  245. return nodePlugins
  246. }
  247. return {
  248. input: resolve(entryFile),
  249. // Global and Browser ESM builds inlines everything so that they can be
  250. // used alone.
  251. external: resolveExternal(),
  252. plugins: [
  253. json({
  254. namedExports: false
  255. }),
  256. alias({
  257. entries
  258. }),
  259. enumPlugin,
  260. ...resolveReplace(),
  261. esbuild({
  262. tsconfig: path.resolve(__dirname, 'tsconfig.json'),
  263. sourceMap: output.sourcemap,
  264. minify: false,
  265. target: isServerRenderer || isNodeBuild ? 'es2019' : 'es2015',
  266. define: resolveDefine()
  267. }),
  268. ...resolveNodePlugins(),
  269. ...plugins
  270. ],
  271. output,
  272. onwarn: (msg, warn) => {
  273. if (!/Circular/.test(msg)) {
  274. warn(msg)
  275. }
  276. },
  277. treeshake: {
  278. moduleSideEffects: false
  279. }
  280. }
  281. }
  282. function createProductionConfig(format) {
  283. return createConfig(format, {
  284. file: resolve(`dist/${name}.${format}.prod.js`),
  285. format: outputConfigs[format].format
  286. })
  287. }
  288. function createMinifiedConfig(format) {
  289. return createConfig(
  290. format,
  291. {
  292. file: outputConfigs[format].file.replace(/\.js$/, '.prod.js'),
  293. format: outputConfigs[format].format
  294. },
  295. [
  296. terser({
  297. module: /^esm/.test(format),
  298. compress: {
  299. ecma: 2015,
  300. pure_getters: true
  301. },
  302. safari10: true
  303. })
  304. ]
  305. )
  306. }
  307. // temporary patch for https://github.com/nodejs/cjs-module-lexer/issues/79
  308. //
  309. // When importing a cjs module from esm, Node.js uses cjs-module-lexer to
  310. // detect * re-exports from other packages. However, the detection logic is
  311. // fragile and breaks when Rollup generates different code for the re-exports.
  312. // We were locked on an old version of Rollup because of this.
  313. //
  314. // The latest versions of Node ships an updated version of cjs-module-lexer that
  315. // has fixed https://github.com/nodejs/cjs-module-lexer/issues/38, however we
  316. // still need to support older versions of Node that does not have the latest
  317. // version of cjs-module-lexer (Node < 14.18)
  318. //
  319. // At the same time, we want to upgrade to Rollup 3 so we are not forever locked
  320. // on an old version of Rollup.
  321. //
  322. // What this patch does:
  323. // 1. Rewrite the for...in loop to Object.keys() so cjs-module-lexer can find it
  324. // The for...in loop is only used when output.externalLiveBindings is set to
  325. // false, and we do want to set it to false to avoid perf costs during SSR.
  326. // 2. Also remove exports.hasOwnProperty check, which breaks the detection in
  327. // Node.js versions that
  328. //
  329. // TODO in the future, we should no longer rely on this if we inline all deps
  330. // in the main `vue` package.
  331. function cjsReExportsPatchPlugin() {
  332. const matcher =
  333. /for \(var k in (\w+)\) {(\s+if \(k !== 'default') && !exports.hasOwnProperty\(k\)(\) exports\[k\] = (?:\w+)\[k\];\s+)}/
  334. return {
  335. name: 'patch-cjs-re-exports',
  336. renderChunk(code, _, options) {
  337. if (matcher.test(code)) {
  338. return code.replace(matcher, (_, r1, r2, r3) => {
  339. return `Object.keys(${r1}).forEach(function(k) {${r2}${r3}});`
  340. })
  341. } else if (options.file.endsWith('packages/vue/dist/vue.cjs.js')) {
  342. // make sure we don't accidentally miss the rewrite in case Rollup
  343. // changes the output again.
  344. throw new Error('cjs build re-exports rewrite failed.')
  345. }
  346. }
  347. }
  348. }