| 1 | import { getImportSource, getRequireSource } from "./utils"; |
| 2 | import type { Visitor } from "@babel/traverse"; |
| 3 | import type { PluginObject, PluginPass } from "@babel/core"; |
| 4 | |
| 5 | function isRegeneratorSource(source: string) { |
| 6 | return ( |
| 7 | source === "regenerator-runtime/runtime" || |
| 8 | source === "regenerator-runtime/runtime.js" |
| 9 | ); |
| 10 | } |
| 11 | |
| 12 | type State = { |
| 13 | regeneratorImportExcluded: boolean; |
| 14 | }; |
| 15 | |
| 16 | export default function (): PluginObject<State & PluginPass> { |
| 17 | const visitor: Visitor<State & PluginPass> = { |
| 18 | ImportDeclaration(path) { |
| 19 | if (isRegeneratorSource(getImportSource(path))) { |
| 20 | this.regeneratorImportExcluded = true; |
| 21 | path.remove(); |
| 22 | } |
| 23 | }, |
| 24 | Program(path) { |
| 25 | path.get("body").forEach(bodyPath => { |
| 26 | if (isRegeneratorSource(getRequireSource(bodyPath))) { |
| 27 | this.regeneratorImportExcluded = true; |
| 28 | bodyPath.remove(); |
| 29 | } |
| 30 | }); |
| 31 | }, |
| 32 | }; |
| 33 | |
| 34 | return { |
| 35 | name: "preset-env/remove-regenerator", |
| 36 | visitor, |
| 37 | pre() { |
| 38 | this.regeneratorImportExcluded = false; |
| 39 | }, |
| 40 | post() { |
| 41 | if (this.opts.debug && this.regeneratorImportExcluded) { |
| 42 | let filename = this.file.opts.filename; |
| 43 | // normalize filename to generate consistent preset-env test fixtures |
| 44 | if (process.env.BABEL_ENV === "test") { |
| 45 | filename = filename.replace(/\\/g, "/"); |
| 46 | } |
| 47 | console.log( |
| 48 | `\n[${filename}] Based on your targets, regenerator-runtime import excluded.`, |
| 49 | ); |
| 50 | } |
| 51 | }, |
| 52 | }; |
| 53 | } |