index.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. const path = require('path')
  2. const semver = require('semver')
  3. const defaultPolyfills = [
  4. // promise polyfill alone doesn't work in IE,
  5. // needs this as well. see: #1642
  6. 'es.array.iterator',
  7. // this is required for webpack code splitting, vuex etc.
  8. 'es.promise',
  9. // this is needed for object rest spread support in templates
  10. // as vue-template-es2015-compiler 1.8+ compiles it to Object.assign() calls.
  11. 'es.object.assign',
  12. // #2012 es.promise replaces native Promise in FF and causes missing finally
  13. 'es.promise.finally'
  14. ]
  15. const {
  16. default: getTargets,
  17. isRequired
  18. } = require('@babel/helper-compilation-targets')
  19. function getIntersectionTargets (targets, constraintTargets) {
  20. const intersection = Object.keys(constraintTargets).reduce(
  21. (results, browser) => {
  22. // exclude the browsers that the user does not need
  23. if (!targets[browser]) {
  24. return results
  25. }
  26. // if the user-specified version is higher the minimum version that supports esmodule, than use it
  27. results[browser] = semver.gt(
  28. semver.coerce(constraintTargets[browser]),
  29. semver.coerce(targets[browser])
  30. )
  31. ? constraintTargets[browser]
  32. : targets[browser]
  33. return results
  34. },
  35. {}
  36. )
  37. return intersection
  38. }
  39. function getModernTargets (targets) {
  40. const allModernTargets = getTargets(
  41. { esmodules: true },
  42. { ignoreBrowserslistConfig: true }
  43. )
  44. // use the intersection of modern mode browsers and user defined targets config
  45. const result = getIntersectionTargets(targets, allModernTargets)
  46. // webpack 4 uses acorn 6, which does not support newer syntaxes such as optional chaining
  47. // so we have to add samsung 12 as a target to force transpiling these syntaxes
  48. // https://github.com/vuejs/vue-cli/issues/6449#issuecomment-828559068
  49. result.samsung = '12.0.0'
  50. return result
  51. }
  52. function getWCTargets (targets) {
  53. // targeting browsers that at least support ES2015 classes
  54. // https://github.com/babel/babel/blob/v7.9.6/packages/babel-compat-data/data/plugins.json#L194-L204
  55. const allWCTargets = getTargets(
  56. {
  57. browsers: [
  58. 'Chrome >= 46',
  59. 'Firefox >= 45',
  60. 'Safari >= 10',
  61. 'Edge >= 13',
  62. 'iOS >= 10',
  63. 'Electron >= 0.36'
  64. ]
  65. },
  66. { ignoreBrowserslistConfig: true }
  67. )
  68. // use the intersection of browsers supporting Web Components and user defined targets config
  69. return getIntersectionTargets(targets, allWCTargets)
  70. }
  71. function getPolyfills (targets, includes) {
  72. // if no targets specified, include all default polyfills
  73. if (!targets || !Object.keys(targets).length) {
  74. return includes
  75. }
  76. const compatData = require('core-js-compat').data
  77. return includes.filter(item => {
  78. if (!compatData[item]) {
  79. throw new Error(`Cannot find polyfill ${item}, please refer to 'core-js-compat' for a complete list of available modules`)
  80. }
  81. return isRequired(item, targets, { compatData })
  82. })
  83. }
  84. module.exports = (context, options = {}) => {
  85. const presets = []
  86. const plugins = []
  87. const defaultEntryFiles = JSON.parse(process.env.VUE_CLI_ENTRY_FILES || '[]')
  88. // Though in the vue-cli repo, we only use the two environment variables
  89. // for tests, users may have relied on them for some features,
  90. // dropping them may break some projects.
  91. // So in the following blocks we don't directly test the `NODE_ENV`.
  92. // Rather, we turn it into the two commonly used feature flags.
  93. if (!process.env.VUE_CLI_TEST && process.env.NODE_ENV === 'test') {
  94. // Both Jest & Mocha set NODE_ENV to 'test'.
  95. // And both requires the `node` target.
  96. process.env.VUE_CLI_BABEL_TARGET_NODE = 'true'
  97. // Jest runs without bundling so it needs this.
  98. // With the node target, tree shaking is not a necessity,
  99. // so we set it for maximum compatibility.
  100. process.env.VUE_CLI_BABEL_TRANSPILE_MODULES = 'true'
  101. }
  102. // JSX
  103. if (options.jsx !== false) {
  104. let jsxOptions = {}
  105. if (typeof options.jsx === 'object') {
  106. jsxOptions = options.jsx
  107. }
  108. let vueVersion = 2
  109. try {
  110. const Vue = require('vue')
  111. vueVersion = semver.major(Vue.version)
  112. } catch (e) {}
  113. if (vueVersion === 2) {
  114. presets.push([require('@vue/babel-preset-jsx'), jsxOptions])
  115. } else if (vueVersion === 3) {
  116. plugins.push([require('@vue/babel-plugin-jsx'), jsxOptions])
  117. }
  118. }
  119. const runtimePath = path.dirname(require.resolve('@babel/runtime/package.json'))
  120. const runtimeVersion = require('@babel/runtime/package.json').version
  121. const {
  122. polyfills: userPolyfills,
  123. loose = false,
  124. debug = false,
  125. useBuiltIns = 'usage',
  126. modules = false,
  127. bugfixes = true,
  128. targets: rawTargets,
  129. spec,
  130. ignoreBrowserslistConfig,
  131. configPath,
  132. include,
  133. exclude,
  134. shippedProposals,
  135. forceAllTransforms,
  136. decoratorsBeforeExport,
  137. decoratorsLegacy,
  138. // entry file list
  139. entryFiles = defaultEntryFiles,
  140. // Undocumented option of @babel/plugin-transform-runtime.
  141. // When enabled, an absolute path is used when importing a runtime helper after transforming.
  142. // This ensures the transpiled file always use the runtime version required in this package.
  143. // However, this may cause hash inconsistency if the project is moved to another directory.
  144. // So here we allow user to explicit disable this option if hash consistency is a requirement
  145. // and the runtime version is sure to be correct.
  146. absoluteRuntime = runtimePath,
  147. // https://babeljs.io/docs/en/babel-plugin-transform-runtime#version
  148. // By default transform-runtime assumes that @babel/runtime@7.0.0-beta.0 is installed, which means helpers introduced later than 7.0.0-beta.0 will be inlined instead of imported.
  149. // See https://github.com/babel/babel/issues/10261
  150. // And https://github.com/facebook/docusaurus/pull/2111
  151. version = runtimeVersion
  152. } = options
  153. // resolve targets for preset-env
  154. let targets = getTargets(rawTargets, { ignoreBrowserslistConfig, configPath })
  155. // Webpack 4 uses acorn 6 underlyingly;
  156. // The highest ESLint version that Vue CLI v4 supports is 6.x;
  157. // Both can only parse ES2019 syntax + BigInt at most.
  158. // Thus, newer syntaxes such as optional chaining and nullish coalescing won't
  159. // be accept by webpack / ESLint, and must be processed by Babel first.
  160. // Chrome 79 is the last Chrome version that doesn't support these syntaxes.
  161. // So the targets set by the user cannot be higher than Chrome 79.
  162. if (!targets.chrome || semver.gt(targets.chrome, '79.0.0')) {
  163. targets.chrome = '79.0.0'
  164. }
  165. if (process.env.VUE_CLI_BABEL_TARGET_NODE) {
  166. // running tests in Node.js
  167. targets = { node: '12' }
  168. } else if (process.env.VUE_CLI_BUILD_TARGET === 'wc' || process.env.VUE_CLI_BUILD_TARGET === 'wc-async') {
  169. // targeting browsers that at least support ES2015 classes
  170. targets = getWCTargets(targets)
  171. } else if (process.env.VUE_CLI_MODERN_BUILD) {
  172. // targeting browsers that at least support <script type="module">
  173. targets = getModernTargets(targets)
  174. }
  175. // included-by-default polyfills. These are common polyfills that 3rd party
  176. // dependencies may rely on (e.g. Vuex relies on Promise), but since with
  177. // useBuiltIns: 'usage' we won't be running Babel on these deps, they need to
  178. // be force-included.
  179. let polyfills
  180. const buildTarget = process.env.VUE_CLI_BUILD_TARGET || 'app'
  181. if (
  182. buildTarget === 'app' &&
  183. useBuiltIns === 'usage' &&
  184. !process.env.VUE_CLI_BABEL_TARGET_NODE
  185. ) {
  186. polyfills = getPolyfills(targets, userPolyfills || defaultPolyfills)
  187. plugins.push([
  188. require('./polyfillsPlugin'),
  189. { polyfills, entryFiles, useAbsolutePath: !!absoluteRuntime }
  190. ])
  191. } else {
  192. polyfills = []
  193. }
  194. const envOptions = {
  195. bugfixes,
  196. corejs: useBuiltIns ? require('core-js/package.json').version : false,
  197. spec,
  198. loose,
  199. debug,
  200. modules,
  201. targets,
  202. useBuiltIns,
  203. ignoreBrowserslistConfig,
  204. configPath,
  205. include,
  206. exclude: polyfills.concat(exclude || []),
  207. shippedProposals,
  208. forceAllTransforms
  209. }
  210. // cli-plugin-jest sets this to true because Jest runs without bundling
  211. if (process.env.VUE_CLI_BABEL_TRANSPILE_MODULES) {
  212. envOptions.modules = 'commonjs'
  213. if (process.env.VUE_CLI_BABEL_TARGET_NODE) {
  214. // necessary for dynamic import to work in tests
  215. plugins.push(require('babel-plugin-dynamic-import-node'))
  216. }
  217. }
  218. // pass options along to babel-preset-env
  219. presets.unshift([require('@babel/preset-env'), envOptions])
  220. // additional <= stage-3 plugins
  221. // Babel 7 is removing stage presets altogether because people are using
  222. // too many unstable proposals. Let's be conservative in the defaults here.
  223. plugins.push(
  224. require('@babel/plugin-syntax-dynamic-import'),
  225. [require('@babel/plugin-proposal-decorators'), {
  226. decoratorsBeforeExport,
  227. legacy: decoratorsLegacy !== false
  228. }],
  229. [require('@babel/plugin-proposal-class-properties'), { loose }]
  230. )
  231. // transform runtime, but only for helpers
  232. plugins.push([require('@babel/plugin-transform-runtime'), {
  233. regenerator: useBuiltIns !== 'usage',
  234. // polyfills are injected by preset-env & polyfillsPlugin, so no need to add them again
  235. corejs: false,
  236. helpers: useBuiltIns === 'usage',
  237. useESModules: !process.env.VUE_CLI_BABEL_TRANSPILE_MODULES,
  238. absoluteRuntime,
  239. version
  240. }])
  241. return {
  242. sourceType: 'unambiguous',
  243. overrides: [{
  244. exclude: [/@babel[\/|\\\\]runtime/, /core-js/],
  245. presets,
  246. plugins
  247. }, {
  248. // there are some untranspiled code in @babel/runtime
  249. // https://github.com/babel/babel/issues/9903
  250. include: [/@babel[\/|\\\\]runtime/],
  251. presets: [
  252. [require('@babel/preset-env'), envOptions]
  253. ]
  254. }]
  255. }
  256. }
  257. // a special flag to tell @vue/cli-plugin-babel to include @babel/runtime for transpilation
  258. // otherwise the above `include` option won't take effect
  259. process.env.VUE_CLI_TRANSPILE_BABEL_RUNTIME = true