-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathreplace-polyfills.js
59 lines (54 loc) · 1.28 KB
/
replace-polyfills.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
// Babel plugin that looks for `core-js` imports (or requires)
// and replaces them with magic comments to mark the file as
// depending on wp-polyfill.
function replacePolyfills() {
return {
pre() {
this.hasAddedPolyfills = false;
},
visitor: {
Program: {
exit( path ) {
if ( this.hasAddedPolyfills ) {
// Add magic comment to top of file.
path.addComment( 'leading', ' wp:polyfill ' );
}
},
},
// Handle `import` syntax.
ImportDeclaration( path ) {
const source = path?.node?.source;
const name = source?.value || '';
// Look for imports from `core-js`.
if ( name.startsWith( 'core-js/' ) ) {
// Remove import.
path.remove();
this.hasAddedPolyfills = true;
}
},
// Handle `require` syntax.
CallExpression( path ) {
const callee = path?.node?.callee;
const arg = path?.node?.arguments[ 0 ];
if (
! callee ||
! arg ||
callee.type !== 'Identifier' ||
callee.name !== 'require'
) {
return;
}
// Look for requires for `core-js`.
if (
arg.type === 'StringLiteral' &&
arg.value.startsWith( 'core-js/' )
) {
// Remove import.
path.remove();
this.hasAddedPolyfills = true;
}
},
},
};
}
module.exports = replacePolyfills;