polyfillsPlugin.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. const { addSideEffect } = require('@babel/helper-module-imports')
  2. // slightly modifiled from @babel/preset-env/src/utils
  3. // use an absolute path for core-js modules, to fix conflicts of different core-js versions
  4. // TODO: remove the `useAbsolutePath` option in v5,
  5. // because `core-js` is sure to be present in newer projects;
  6. // we only need absolute path for babel runtime helpers, not for polyfills
  7. function getModulePath (mod, useAbsolutePath) {
  8. const modPath =
  9. mod === 'regenerator-runtime'
  10. ? 'regenerator-runtime/runtime'
  11. : `core-js/modules/${mod}`
  12. return useAbsolutePath ? require.resolve(modPath) : modPath
  13. }
  14. function createImport (path, mod, useAbsolutePath) {
  15. return addSideEffect(path, getModulePath(mod, useAbsolutePath))
  16. }
  17. // add polyfill imports to the first file encountered.
  18. module.exports = (
  19. { types },
  20. { polyfills, entryFiles = [], useAbsolutePath }
  21. ) => {
  22. return {
  23. name: 'vue-cli-inject-polyfills',
  24. visitor: {
  25. Program (path, state) {
  26. if (!entryFiles.includes(state.filename)) {
  27. return
  28. }
  29. // imports are injected in reverse order
  30. polyfills
  31. .slice()
  32. .reverse()
  33. .forEach(p => {
  34. createImport(path, p, useAbsolutePath)
  35. })
  36. }
  37. }
  38. }
  39. }