-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
lockCoreJSVersionPlugin.js
49 lines (42 loc) · 1.43 KB
/
lockCoreJSVersionPlugin.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
import { dirname } from 'path';
import { winPath } from 'umi-utils';
import * as types from '@babel/types';
const coreJSPath = dirname(require.resolve('core-js/package.json'));
function isUmiCoreJSPolyfill(oFilename, identifier) {
const filename = winPath(oFilename);
return (
(filename.endsWith('.umi/polyfills.js') || filename.endsWith('.umi-production/polyfills.js')) &&
identifier.startsWith('core-js/')
);
}
function getReplacedCoreJSPath(path) {
return path.replace('core-js/', `${coreJSPath}/`);
}
export default function() {
return {
visitor: {
// handle import statements
ImportDeclaration(path, state) {
const callPathNode = path.node;
if (
types.isLiteral(callPathNode.source) &&
isUmiCoreJSPolyfill(state.filename, callPathNode.source.value)
) {
callPathNode.source.value = getReplacedCoreJSPath(callPathNode.source.value);
}
},
// handle require statements
CallExpression(path, state) {
const callPathNode = path.node;
if (
types.isIdentifier(callPathNode.callee) &&
callPathNode.callee.name === 'require' &&
types.isStringLiteral(callPathNode.arguments[0]) &&
isUmiCoreJSPolyfill(state.filename, callPathNode.arguments[0].value)
) {
callPathNode.arguments[0].value = getReplacedCoreJSPath(callPathNode.arguments[0].value);
}
},
},
};
}