rollup.config.mjs 12 KB

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