index.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. if (process.env.VUE_CLI_BABEL_TARGET_NODE) {
  156. // running tests in Node.js
  157. targets = { node: 'current' }
  158. } else if (process.env.VUE_CLI_BUILD_TARGET === 'wc' || process.env.VUE_CLI_BUILD_TARGET === 'wc-async') {
  159. // targeting browsers that at least support ES2015 classes
  160. targets = getWCTargets(targets)
  161. } else if (process.env.VUE_CLI_MODERN_BUILD) {
  162. // targeting browsers that at least support <script type="module">
  163. targets = getModernTargets(targets)
  164. }
  165. // included-by-default polyfills. These are common polyfills that 3rd party
  166. // dependencies may rely on (e.g. Vuex relies on Promise), but since with
  167. // useBuiltIns: 'usage' we won't be running Babel on these deps, they need to
  168. // be force-included.
  169. let polyfills
  170. const buildTarget = process.env.VUE_CLI_BUILD_TARGET || 'app'
  171. if (
  172. buildTarget === 'app' &&
  173. useBuiltIns === 'usage' &&
  174. !process.env.VUE_CLI_BABEL_TARGET_NODE
  175. ) {
  176. polyfills = getPolyfills(targets, userPolyfills || defaultPolyfills)
  177. plugins.push([
  178. require('./polyfillsPlugin'),
  179. { polyfills, entryFiles, useAbsolutePath: !!absoluteRuntime }
  180. ])
  181. } else {
  182. polyfills = []
  183. }
  184. const envOptions = {
  185. bugfixes,
  186. corejs: useBuiltIns ? require('core-js/package.json').version : false,
  187. spec,
  188. loose,
  189. debug,
  190. modules,
  191. targets,
  192. useBuiltIns,
  193. ignoreBrowserslistConfig,
  194. configPath,
  195. include,
  196. exclude: polyfills.concat(exclude || []),
  197. shippedProposals,
  198. forceAllTransforms
  199. }
  200. // cli-plugin-jest sets this to true because Jest runs without bundling
  201. if (process.env.VUE_CLI_BABEL_TRANSPILE_MODULES) {
  202. envOptions.modules = 'commonjs'
  203. if (process.env.VUE_CLI_BABEL_TARGET_NODE) {
  204. // necessary for dynamic import to work in tests
  205. plugins.push(require('babel-plugin-dynamic-import-node'))
  206. }
  207. }
  208. // pass options along to babel-preset-env
  209. presets.unshift([require('@babel/preset-env'), envOptions])
  210. // additional <= stage-3 plugins
  211. // Babel 7 is removing stage presets altogether because people are using
  212. // too many unstable proposals. Let's be conservative in the defaults here.
  213. plugins.push(
  214. require('@babel/plugin-syntax-dynamic-import'),
  215. [require('@babel/plugin-proposal-decorators'), {
  216. decoratorsBeforeExport,
  217. legacy: decoratorsLegacy !== false
  218. }],
  219. [require('@babel/plugin-proposal-class-properties'), { loose }]
  220. )
  221. // transform runtime, but only for helpers
  222. plugins.push([require('@babel/plugin-transform-runtime'), {
  223. regenerator: useBuiltIns !== 'usage',
  224. // polyfills are injected by preset-env & polyfillsPlugin, so no need to add them again
  225. corejs: false,
  226. helpers: useBuiltIns === 'usage',
  227. useESModules: !process.env.VUE_CLI_BABEL_TRANSPILE_MODULES,
  228. absoluteRuntime,
  229. version
  230. }])
  231. return {
  232. sourceType: 'unambiguous',
  233. overrides: [{
  234. exclude: [/@babel[\/|\\\\]runtime/, /core-js/],
  235. presets,
  236. plugins
  237. }, {
  238. // there are some untranspiled code in @babel/runtime
  239. // https://github.com/babel/babel/issues/9903
  240. include: [/@babel[\/|\\\\]runtime/],
  241. presets: [
  242. [require('@babel/preset-env'), envOptions]
  243. ]
  244. }]
  245. }
  246. }
  247. // a special flag to tell @vue/cli-plugin-babel to include @babel/runtime for transpilation
  248. // otherwise the above `include` option won't take effect
  249. process.env.VUE_CLI_TRANSPILE_BABEL_RUNTIME = true