rollup.config.mjs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. if (isGlobalBuild || isBrowserESMBuild || isCompatPackage) {
  130. if (!packageOptions.enableNonBrowserBranches) {
  131. // normal browser builds - non-browser only imports are tree-shaken,
  132. // they are only listed here to suppress warnings.
  133. external = ['source-map', '@babel/parser', 'estree-walker']
  134. }
  135. } else {
  136. // Node / esm-bundler builds.
  137. // externalize all direct deps unless it's the compat build.
  138. external = [
  139. ...Object.keys(pkg.dependencies || {}),
  140. ...Object.keys(pkg.peerDependencies || {}),
  141. ...['path', 'url', 'stream'] // for @vue/compiler-sfc / server-renderer
  142. ]
  143. }
  144. // we are bundling forked consolidate.js in compiler-sfc which dynamically
  145. // requires a ton of template engines which should be ignored.
  146. let cjsIgnores = []
  147. if (pkg.name === '@vue/compiler-sfc') {
  148. cjsIgnores = [
  149. ...Object.keys(consolidatePkg.devDependencies),
  150. 'vm',
  151. 'crypto',
  152. 'react-dom/server',
  153. 'teacup/lib/express',
  154. 'arc-templates/dist/es5',
  155. 'then-pug',
  156. 'then-jade'
  157. ]
  158. }
  159. const nodePlugins =
  160. (format === 'cjs' && Object.keys(pkg.devDependencies || {}).length) ||
  161. packageOptions.enableNonBrowserBranches
  162. ? [
  163. commonJS({
  164. sourceMap: false,
  165. ignore: cjsIgnores
  166. }),
  167. ...(format === 'cjs' ? [] : [polyfillNode()]),
  168. nodeResolve()
  169. ]
  170. : []
  171. return {
  172. input: resolve(entryFile),
  173. // Global and Browser ESM builds inlines everything so that they can be
  174. // used alone.
  175. external,
  176. plugins: [
  177. json({
  178. namedExports: false
  179. }),
  180. tsPlugin,
  181. createReplacePlugin(
  182. isProductionBuild,
  183. isBundlerESMBuild,
  184. isBrowserESMBuild,
  185. // isBrowserBuild?
  186. (isGlobalBuild || isBrowserESMBuild || isBundlerESMBuild) &&
  187. !packageOptions.enableNonBrowserBranches,
  188. isGlobalBuild,
  189. isNodeBuild,
  190. isCompatBuild,
  191. isServerRenderer
  192. ),
  193. ...nodePlugins,
  194. ...plugins
  195. ],
  196. output,
  197. onwarn: (msg, warn) => {
  198. if (!/Circular/.test(msg)) {
  199. warn(msg)
  200. }
  201. },
  202. treeshake: {
  203. moduleSideEffects: false
  204. }
  205. }
  206. }
  207. function createReplacePlugin(
  208. isProduction,
  209. isBundlerESMBuild,
  210. isBrowserESMBuild,
  211. isBrowserBuild,
  212. isGlobalBuild,
  213. isNodeBuild,
  214. isCompatBuild,
  215. isServerRenderer
  216. ) {
  217. const replacements = {
  218. __COMMIT__: `"${process.env.COMMIT}"`,
  219. __VERSION__: `"${masterVersion}"`,
  220. __DEV__: isBundlerESMBuild
  221. ? // preserve to be handled by bundlers
  222. `(process.env.NODE_ENV !== 'production')`
  223. : // hard coded dev/prod builds
  224. !isProduction,
  225. // this is only used during Vue's internal tests
  226. __TEST__: false,
  227. // If the build is expected to run directly in the browser (global / esm builds)
  228. __BROWSER__: isBrowserBuild,
  229. __GLOBAL__: isGlobalBuild,
  230. __ESM_BUNDLER__: isBundlerESMBuild,
  231. __ESM_BROWSER__: isBrowserESMBuild,
  232. // is targeting Node (SSR)?
  233. __NODE_JS__: isNodeBuild,
  234. // need SSR-specific branches?
  235. __SSR__: isNodeBuild || isBundlerESMBuild || isServerRenderer,
  236. // for compiler-sfc browser build inlined deps
  237. ...(isBrowserESMBuild
  238. ? {
  239. 'process.env': '({})',
  240. 'process.platform': '""',
  241. 'process.stdout': 'null'
  242. }
  243. : {}),
  244. // 2.x compat build
  245. __COMPAT__: isCompatBuild,
  246. // feature flags
  247. __FEATURE_SUSPENSE__: true,
  248. __FEATURE_OPTIONS_API__: isBundlerESMBuild ? `__VUE_OPTIONS_API__` : true,
  249. __FEATURE_PROD_DEVTOOLS__: isBundlerESMBuild
  250. ? `__VUE_PROD_DEVTOOLS__`
  251. : false,
  252. ...(isProduction && isBrowserBuild
  253. ? {
  254. 'context.onError(': `/*#__PURE__*/ context.onError(`,
  255. 'emitError(': `/*#__PURE__*/ emitError(`,
  256. 'createCompilerError(': `/*#__PURE__*/ createCompilerError(`,
  257. 'createDOMCompilerError(': `/*#__PURE__*/ createDOMCompilerError(`
  258. }
  259. : {})
  260. }
  261. // allow inline overrides like
  262. //__RUNTIME_COMPILE__=true yarn build runtime-core
  263. Object.keys(replacements).forEach(key => {
  264. if (key in process.env) {
  265. replacements[key] = process.env[key]
  266. }
  267. })
  268. return replace({
  269. // @ts-ignore
  270. values: replacements,
  271. preventAssignment: true
  272. })
  273. }
  274. function createProductionConfig(format) {
  275. return createConfig(format, {
  276. file: resolve(`dist/${name}.${format}.prod.js`),
  277. format: outputConfigs[format].format
  278. })
  279. }
  280. function createMinifiedConfig(format) {
  281. return createConfig(
  282. format,
  283. {
  284. file: outputConfigs[format].file.replace(/\.js$/, '.prod.js'),
  285. format: outputConfigs[format].format
  286. },
  287. [
  288. terser({
  289. module: /^esm/.test(format),
  290. compress: {
  291. ecma: 2015,
  292. pure_getters: true
  293. },
  294. safari10: true
  295. })
  296. ]
  297. )
  298. }