-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
28 lines (27 loc) · 1.05 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
module.exports = ({ types: t }) => ({
name: 'transform-string-to-import',
inherits: require('babel-plugin-syntax-jsx'),
pre() {
this.idents = {}
},
visitor: {
StringLiteral(path, { opts: { prefix = '~' } }) {
const { node } = path
if (!node.value.startsWith(prefix)) return
const file = path.findParent(path => path.parent.type === 'File')
const requirePath = node.value.replace(prefix, '')
if (!this.idents[requirePath]) {
this.idents[requirePath] = file.scope.generateUidIdentifier(requirePath)
file.unshiftContainer('body',
t.importDeclaration(
[t.importDefaultSpecifier(this.idents[requirePath])],
t.stringLiteral(requirePath)
)
)
}
path.replaceWith(t.isJSXAttribute(path.parent)
? t.jSXExpressionContainer(this.idents[requirePath])
: this.idents[requirePath])
}
}
})