index.js 8.9 KB

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