forked from giuseppeg/babel-plugin-classnames
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (62 loc) · 1.91 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
function babelPluginClassNames({ types: t }) {
const cloneNode = t.cloneNode || t.cloneDeep
return {
name: "babel-plugin-classnames",
visitor: {
Program: {
enter(path, state) {
state.classNamesIdentifier = path.scope.generateUidIdentifier('classNames')
},
exit(path, state) {
if (state.hasClassNames) {
const importDeclaration = t.importDeclaration(
[
state.opts.importName
? t.importSpecifier(
state.classNamesIdentifier,
t.identifier(state.opts.importName)
)
: t.importDefaultSpecifier(state.classNamesIdentifier)
],
t.stringLiteral(state.opts.packageName || 'classnames')
)
path.node.body.unshift(importDeclaration)
}
}
},
JSXAttribute(path, state) {
if (path.node.name.name !== 'className') {
return
}
const value = path.get('value')
if (!value.isJSXExpressionContainer()) {
return
}
const expression = value.get('expression')
if (expression.isArrayExpression()) {
expression.replaceWith(
t.callExpression(
cloneNode(state.classNamesIdentifier),
expression.get('elements').map(e => cloneNode(e.node)),
)
)
} else if (state.opts.transformObjects && expression.isObjectExpression()) {
expression.replaceWith(
t.callExpression(
cloneNode(state.classNamesIdentifier),
[cloneNode(expression.node)]
)
)
} else {
return
}
state.hasClassNames = true
}
}
}
}
exports = module.exports = babelPluginClassNames
exports.default = babelPluginClassNames
Object.defineProperty(exports, "__esModule", {
value: true
})