| 1 | import { getImportSource, getRequireSource, isPolyfillSource } from "./utils"; |
| 2 | |
| 3 | import type { NodePath } from "@babel/traverse"; |
| 4 | import type * as t from "@babel/types"; |
| 5 | |
| 6 | const BABEL_POLYFILL_DEPRECATION = ` |
| 7 | \`@babel/polyfill\` is deprecated. Please, use required parts of \`core-js\` |
| 8 | and \`regenerator-runtime/runtime\` separately`; |
| 9 | |
| 10 | const NO_DIRECT_POLYFILL_IMPORT = ` |
| 11 | When setting \`useBuiltIns: 'usage'\`, polyfills are automatically imported when needed. |
| 12 | Please remove the direct import of \`SPECIFIER\` or use \`useBuiltIns: 'entry'\` instead.`; |
| 13 | |
| 14 | export default function ( |
| 15 | { template }: any, |
| 16 | { regenerator, deprecated, usage }: any, |
| 17 | ) { |
| 18 | return { |
| 19 | name: "preset-env/replace-babel-polyfill", |
| 20 | visitor: { |
| 21 | ImportDeclaration(path: NodePath<t.ImportDeclaration>) { |
| 22 | const src = getImportSource(path); |
| 23 | if (usage && isPolyfillSource(src)) { |
| 24 | console.warn(NO_DIRECT_POLYFILL_IMPORT.replace("SPECIFIER", src)); |
| 25 | if (!deprecated) path.remove(); |
| 26 | } else if (src === "@babel/polyfill") { |
| 27 | if (deprecated) { |
| 28 | console.warn(BABEL_POLYFILL_DEPRECATION); |
| 29 | } else if (regenerator) { |
| 30 | path.replaceWithMultiple(template.ast` |
| 31 | import "core-js"; |
| 32 | import "regenerator-runtime/runtime.js"; |
| 33 | `); |
| 34 | } else { |
| 35 | path.replaceWith(template.ast` |
| 36 | import "core-js"; |
| 37 | `); |
| 38 | } |
| 39 | } |
| 40 | }, |
| 41 | Program(path: NodePath<t.Program>) { |
| 42 | path.get("body").forEach(bodyPath => { |
| 43 | const src = getRequireSource(bodyPath); |
| 44 | if (usage && isPolyfillSource(src)) { |
| 45 | console.warn(NO_DIRECT_POLYFILL_IMPORT.replace("SPECIFIER", src)); |
| 46 | if (!deprecated) bodyPath.remove(); |
| 47 | } else if (src === "@babel/polyfill") { |
| 48 | if (deprecated) { |
| 49 | console.warn(BABEL_POLYFILL_DEPRECATION); |
| 50 | } else if (regenerator) { |
| 51 | bodyPath.replaceWithMultiple(template.ast` |
| 52 | require("core-js"); |
| 53 | require("regenerator-runtime/runtime.js"); |
| 54 | `); |
| 55 | } else { |
| 56 | bodyPath.replaceWith(template.ast` |
| 57 | require("core-js"); |
| 58 | `); |
| 59 | } |
| 60 | } |
| 61 | }); |
| 62 | }, |
| 63 | }, |
| 64 | }; |
| 65 | } |