rollup.config.mjs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. return {
  176. input: resolve(entryFile),
  177. // Global and Browser ESM builds inlines everything so that they can be
  178. // used alone.
  179. external,
  180. plugins: [
  181. json({
  182. namedExports: false
  183. }),
  184. tsPlugin,
  185. createReplacePlugin(
  186. isProductionBuild,
  187. isBundlerESMBuild,
  188. isBrowserESMBuild,
  189. // isBrowserBuild?
  190. (isGlobalBuild || isBrowserESMBuild || isBundlerESMBuild) &&
  191. !packageOptions.enableNonBrowserBranches,
  192. isGlobalBuild,
  193. isNodeBuild,
  194. isCompatBuild,
  195. isServerRenderer
  196. ),
  197. ...nodePlugins,
  198. ...plugins
  199. ],
  200. output,
  201. onwarn: (msg, warn) => {
  202. if (!/Circular/.test(msg)) {
  203. warn(msg)
  204. }
  205. },
  206. treeshake: {
  207. moduleSideEffects: false
  208. }
  209. }
  210. }
  211. function createReplacePlugin(
  212. isProduction,
  213. isBundlerESMBuild,
  214. isBrowserESMBuild,
  215. isBrowserBuild,
  216. isGlobalBuild,
  217. isNodeBuild,
  218. isCompatBuild,
  219. isServerRenderer
  220. ) {
  221. const replacements = {
  222. __COMMIT__: `"${process.env.COMMIT}"`,
  223. __VERSION__: `"${masterVersion}"`,
  224. __DEV__: isBundlerESMBuild
  225. ? // preserve to be handled by bundlers
  226. `(process.env.NODE_ENV !== 'production')`
  227. : // hard coded dev/prod builds
  228. !isProduction,
  229. // this is only used during Vue's internal tests
  230. __TEST__: false,
  231. // If the build is expected to run directly in the browser (global / esm builds)
  232. __BROWSER__: isBrowserBuild,
  233. __GLOBAL__: isGlobalBuild,
  234. __ESM_BUNDLER__: isBundlerESMBuild,
  235. __ESM_BROWSER__: isBrowserESMBuild,
  236. // is targeting Node (SSR)?
  237. __NODE_JS__: isNodeBuild,
  238. // need SSR-specific branches?
  239. __SSR__: isNodeBuild || isBundlerESMBuild || isServerRenderer,
  240. // for compiler-sfc browser build inlined deps
  241. ...(isBrowserESMBuild
  242. ? {
  243. 'process.env': '({})',
  244. 'process.platform': '""',
  245. 'process.stdout': 'null'
  246. }
  247. : {}),
  248. // 2.x compat build
  249. __COMPAT__: isCompatBuild,
  250. // feature flags
  251. __FEATURE_SUSPENSE__: true,
  252. __FEATURE_OPTIONS_API__: isBundlerESMBuild ? `__VUE_OPTIONS_API__` : true,
  253. __FEATURE_PROD_DEVTOOLS__: isBundlerESMBuild
  254. ? `__VUE_PROD_DEVTOOLS__`
  255. : false,
  256. ...(isProduction && isBrowserBuild
  257. ? {
  258. 'context.onError(': `/*#__PURE__*/ context.onError(`,
  259. 'emitError(': `/*#__PURE__*/ emitError(`,
  260. 'createCompilerError(': `/*#__PURE__*/ createCompilerError(`,
  261. 'createDOMCompilerError(': `/*#__PURE__*/ createDOMCompilerError(`
  262. }
  263. : {})
  264. }
  265. // allow inline overrides like
  266. //__RUNTIME_COMPILE__=true yarn build runtime-core
  267. Object.keys(replacements).forEach(key => {
  268. if (key in process.env) {
  269. replacements[key] = process.env[key]
  270. }
  271. })
  272. return replace({
  273. // @ts-ignore
  274. values: replacements,
  275. preventAssignment: true
  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. }