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