-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransform-plugins.js
66 lines (60 loc) · 2.33 KB
/
transform-plugins.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
// transform from object into cssobj config, with plugins transformed
var objutil = require('objutil')
module.exports = function (babel) {
var t = babel.types
return {
visitor: {
Program (path, state) {
var firstExp = path.node.body[0]
var option = state.opts
option = objutil.defaults(
option,
{ names: {} }
)
// only transform !{plugins:[]}
if (!t.isExpressionStatement(firstExp)
|| !t.isUnaryExpression(firstExp.expression, {operator: '!'})
|| !t.isObjectExpression(firstExp.expression.argument)) return
// get target expression
var node = firstExp.expression.argument
// get "plugins" prop, it's from JSON.stringify
var pluginsNode = node.properties.filter(function (v) {
return getKeyValue(v) === 'plugins'
&& t.isArrayExpression(v.value)
}).shift()
// plugins transform part
if (pluginsNode) {
// only transform literal keys with plugin names
var elements = pluginsNode.value.elements
var cssobjImports = path.node.cssobjImports = []
for (var v, prop, value, i = 0; i < elements.length; i++) {
v = elements[i]
if (t.isLiteral(v) && (value = '', prop = v.value)
|| t.isObjectExpression(v)
&& v.properties.length == 1
&& (prop = getKeyValue(v.properties[0]))
// plugin name cannot be below keywords
&& ['selector', 'value', 'post'].indexOf(prop) < 0
&& (value = v.properties[0].value)) {
var pluginNS = option.names[prop]
var pluginIden = pluginNS && pluginNS.name || 'cssobj_plugin_' + prop.replace(/-/g, '_')
elements[i] = t.callExpression(
t.identifier(pluginIden),
value ? [value] : []
)
cssobjImports.push(t.importDeclaration(
[t.importDefaultSpecifier(t.identifier(pluginIden))],
t.stringLiteral(pluginNS && pluginNS.path || 'cssobj-plugin-' + prop)
))
}
}
path.node.cssobjConfig = node
}
}
}
}
function getKeyValue (v) {
if (t.isLiteral(v.key)) return v.key.value
if (t.isIdentifier(v.key)) return v.key.name
}
}