rollup.config.js 9.2 KB

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