rollup.config.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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 isNodeBuild = format === 'cjs'
  79. const isGlobalBuild = /global/.test(format)
  80. const isCompatPackage = pkg.name === '@vue/compat'
  81. const isCompatBuild = !!packageOptions.compat
  82. output.exports = isCompatPackage ? 'auto' : 'named'
  83. output.sourcemap = !!process.env.SOURCE_MAP
  84. output.externalLiveBindings = false
  85. if (isGlobalBuild) {
  86. output.name = packageOptions.name
  87. }
  88. const shouldEmitDeclarations =
  89. pkg.types && process.env.TYPES != null && !hasTSChecked
  90. const tsPlugin = ts({
  91. check: process.env.NODE_ENV === 'production' && !hasTSChecked,
  92. tsconfig: path.resolve(__dirname, 'tsconfig.json'),
  93. cacheRoot: path.resolve(__dirname, 'node_modules/.rts2_cache'),
  94. tsconfigOverride: {
  95. compilerOptions: {
  96. sourceMap: output.sourcemap,
  97. declaration: shouldEmitDeclarations,
  98. declarationMap: shouldEmitDeclarations
  99. },
  100. exclude: ['**/__tests__', 'test-dts']
  101. }
  102. })
  103. // we only need to check TS and generate declarations once for each build.
  104. // it also seems to run into weird issues when checking multiple times
  105. // during a single build.
  106. hasTSChecked = true
  107. let entryFile = /runtime$/.test(format) ? `src/runtime.ts` : `src/index.ts`
  108. // the compat build needs both default AND named exports. This will cause
  109. // Rollup to complain for non-ESM targets, so we use separate entries for
  110. // esm vs. non-esm builds.
  111. if (isCompatPackage && (isBrowserESMBuild || isBundlerESMBuild)) {
  112. entryFile = /runtime$/.test(format)
  113. ? `src/esm-runtime.ts`
  114. : `src/esm-index.ts`
  115. }
  116. let external = []
  117. if (isGlobalBuild || isBrowserESMBuild || isCompatPackage) {
  118. if (!packageOptions.enableNonBrowserBranches) {
  119. // normal browser builds - non-browser only imports are tree-shaken,
  120. // they are only listed here to suppress warnings.
  121. external = ['source-map', '@babel/parser', 'estree-walker']
  122. }
  123. } else {
  124. // Node / esm-bundler builds.
  125. // externalize all direct deps unless it's the compat build.
  126. external = [
  127. ...Object.keys(pkg.dependencies || {}),
  128. ...Object.keys(pkg.peerDependencies || {}),
  129. ...['path', 'url', 'stream'] // for @vue/compiler-sfc / server-renderer
  130. ]
  131. }
  132. // we are bundling forked consolidate.js in compiler-sfc which dynamically
  133. // requires a ton of template engines which should be ignored.
  134. let cjsIgnores = []
  135. if (pkg.name === '@vue/compiler-sfc') {
  136. cjsIgnores = [
  137. ...Object.keys(require('@vue/consolidate/package.json').devDependencies),
  138. 'vm',
  139. 'crypto',
  140. 'react-dom/server',
  141. 'teacup/lib/express',
  142. 'arc-templates/dist/es5',
  143. 'then-pug',
  144. 'then-jade'
  145. ]
  146. }
  147. const nodePlugins =
  148. (format === 'cjs' && Object.keys(pkg.devDependencies || {}).length) ||
  149. packageOptions.enableNonBrowserBranches
  150. ? [
  151. // @ts-ignore
  152. require('@rollup/plugin-commonjs')({
  153. sourceMap: false,
  154. ignore: cjsIgnores
  155. }),
  156. ...(format === 'cjs'
  157. ? []
  158. : // @ts-ignore
  159. [require('rollup-plugin-polyfill-node')()]),
  160. require('@rollup/plugin-node-resolve').nodeResolve()
  161. ]
  162. : []
  163. return {
  164. input: resolve(entryFile),
  165. // Global and Browser ESM builds inlines everything so that they can be
  166. // used alone.
  167. external,
  168. plugins: [
  169. json({
  170. namedExports: false
  171. }),
  172. tsPlugin,
  173. createReplacePlugin(
  174. isProductionBuild,
  175. isBundlerESMBuild,
  176. isBrowserESMBuild,
  177. // isBrowserBuild?
  178. (isGlobalBuild || isBrowserESMBuild || isBundlerESMBuild) &&
  179. !packageOptions.enableNonBrowserBranches,
  180. isGlobalBuild,
  181. isNodeBuild,
  182. isCompatBuild
  183. ),
  184. ...nodePlugins,
  185. ...plugins
  186. ],
  187. output,
  188. onwarn: (msg, warn) => {
  189. if (!/Circular/.test(msg)) {
  190. warn(msg)
  191. }
  192. },
  193. treeshake: {
  194. moduleSideEffects: false
  195. }
  196. }
  197. }
  198. function createReplacePlugin(
  199. isProduction,
  200. isBundlerESMBuild,
  201. isBrowserESMBuild,
  202. isBrowserBuild,
  203. isGlobalBuild,
  204. isNodeBuild,
  205. isCompatBuild
  206. ) {
  207. const replacements = {
  208. __COMMIT__: `"${process.env.COMMIT}"`,
  209. __VERSION__: `"${masterVersion}"`,
  210. __DEV__: isBundlerESMBuild
  211. ? // preserve to be handled by bundlers
  212. `(process.env.NODE_ENV !== 'production')`
  213. : // hard coded dev/prod builds
  214. !isProduction,
  215. // this is only used during Vue's internal tests
  216. __TEST__: false,
  217. // If the build is expected to run directly in the browser (global / esm builds)
  218. __BROWSER__: isBrowserBuild,
  219. __GLOBAL__: isGlobalBuild,
  220. __ESM_BUNDLER__: isBundlerESMBuild,
  221. __ESM_BROWSER__: isBrowserESMBuild,
  222. // is targeting Node (SSR)?
  223. __NODE_JS__: isNodeBuild,
  224. // need SSR-specific branches?
  225. __SSR__: isNodeBuild || isBundlerESMBuild,
  226. // for compiler-sfc browser build inlined deps
  227. ...(isBrowserESMBuild
  228. ? {
  229. 'process.env': '({})',
  230. 'process.platform': '""',
  231. 'process.stdout': 'null'
  232. }
  233. : {}),
  234. // 2.x compat build
  235. __COMPAT__: isCompatBuild,
  236. // feature flags
  237. __FEATURE_SUSPENSE__: true,
  238. __FEATURE_OPTIONS_API__: isBundlerESMBuild ? `__VUE_OPTIONS_API__` : true,
  239. __FEATURE_PROD_DEVTOOLS__: isBundlerESMBuild
  240. ? `__VUE_PROD_DEVTOOLS__`
  241. : false,
  242. ...(isProduction && isBrowserBuild
  243. ? {
  244. 'context.onError(': `/*#__PURE__*/ context.onError(`,
  245. 'emitError(': `/*#__PURE__*/ emitError(`,
  246. 'createCompilerError(': `/*#__PURE__*/ createCompilerError(`,
  247. 'createDOMCompilerError(': `/*#__PURE__*/ createDOMCompilerError(`
  248. }
  249. : {})
  250. }
  251. // allow inline overrides like
  252. //__RUNTIME_COMPILE__=true yarn build runtime-core
  253. Object.keys(replacements).forEach(key => {
  254. if (key in process.env) {
  255. replacements[key] = process.env[key]
  256. }
  257. })
  258. return replace({
  259. // @ts-ignore
  260. values: replacements,
  261. preventAssignment: true
  262. })
  263. }
  264. function createProductionConfig(format) {
  265. return createConfig(format, {
  266. file: resolve(`dist/${name}.${format}.prod.js`),
  267. format: outputConfigs[format].format
  268. })
  269. }
  270. function createMinifiedConfig(format) {
  271. const { terser } = require('rollup-plugin-terser')
  272. return createConfig(
  273. format,
  274. {
  275. file: outputConfigs[format].file.replace(/\.js$/, '.prod.js'),
  276. format: outputConfigs[format].format
  277. },
  278. [
  279. terser({
  280. module: /^esm/.test(format),
  281. compress: {
  282. ecma: 2015,
  283. pure_getters: true
  284. },
  285. safari10: true
  286. })
  287. ]
  288. )
  289. }