forked from kentcdodds/babel-codemod-example
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.js
More file actions
45 lines (44 loc) · 1.45 KB
/
plugin.js
File metadata and controls
45 lines (44 loc) · 1.45 KB
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
module.exports = function(babel) {
const { types: t } = babel
// could just use https://www.npmjs.com/package/is-builtin-module
const nodeModules = [
'fs', 'path', 'child_process',
]
return {
name: 'node-esmodule', // not required
visitor: {
ImportDeclaration(path) {
const specifiers = []
let defaultSpecifier
path.get('specifiers').forEach(specifier => {
if (t.isImportSpecifier(specifier)) {
specifiers.push(specifier)
} else {
defaultSpecifier = specifier
}
})
const {node: {value: source}} = path.get('source')
if (!specifiers.length || !nodeModules.includes(source)) {
return
}
let memberObjectNameIdentifier
if (defaultSpecifier) {
memberObjectNameIdentifier = defaultSpecifier.node.local
} else {
memberObjectNameIdentifier = path.scope.generateUidIdentifier(source)
path.node.specifiers.push(t.importDefaultSpecifier(memberObjectNameIdentifier))
}
specifiers.forEach(specifier => {
const {node: {imported: {name}}} = specifier
const {referencePaths} = specifier.scope.getBinding(name)
referencePaths.forEach(refPath => {
refPath.replaceWith(
t.memberExpression(memberObjectNameIdentifier, t.identifier(name))
)
})
specifier.remove()
})
}
}
}
}