rollup.config.mjs 12 KB

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