index.js 9.1 KB

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