-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
55 lines (47 loc) · 1.59 KB
/
index.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
const { declare } = require('@babel/helper-plugin-utils');
const { importDefaultSpecifier } = require('./utils');
module.exports = declare(api => {
api.assertVersion(7);
function IdentifierVisitor(path) {
if (!this.provides) return;
const parent = path.parent;
if (!parent) return;
if (['FunctionDeclaration', 'ClassMethod', 'ObjectMethod'].includes(parent.type)) return;
if (parent.type === 'ObjectProperty' && parent.key === path.node) return;
if (parent.type === 'MemberExpression' && parent.object !== path.node) return;
if (parent.type === 'VariableDeclarator' && parent.id === path.node) return;
let identifier = path.node.name;
if (path.scope.bindings[identifier] || this.handled[identifier]) return;
this.handled[identifier] = true;
let provide = this.provides[identifier];
if (provide) {
this.addDefaultImport(path, identifier, provide);
}
}
return {
name: 'babel-plugin-provide',
visitor: {
Program: {
enter(nodePath, state) {
const {
file: {
opts: { filename }
},
opts = {}
} = state;
const ctx = {
provides: opts,
handled: {},
addDefaultImport(path, varName, libraryName) {
if (typeof libraryName === 'function') libraryName = libraryName(filename, state);
libraryName && importDefaultSpecifier(path, varName, libraryName);
}
};
nodePath.traverse({
Identifier: IdentifierVisitor
}, ctx);
},
},
}
};
});