-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
63 lines (58 loc) · 1.46 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
import { atRule } from 'postcss';
const postcss = require('postcss')
const schema = {
component: {
alias: 'b',
separator: '.'
},
descendent: {
alias: 'e',
separator: '-'
},
modifier: {
alias: 'm',
separator: '--'
},
when: {
alias: 'w',
separator: '_'
}
}
module.exports = postcss.plugin('postcss-bem', function (opts) {
function getAtruleSelector (atRule, paramName) {
let selectorArray = [schema[atRule.name].separator, paramName]
let theParent = atRule.parent
while (theParent && theParent.type !== 'root') {
selectorArray.unshift(`${schema[theParent.name].separator}${theParent.params}`)
theParent = theParent.parent
}
return selectorArray.join('')
}
function processAtrule (css, atRule) {
let ruleName = atRule.name
if (!schema.hasOwnProperty(ruleName)) {
throw new Error(`you have written an unsupported type of bem declaration ${ruleName}`)
}
let paramName = atRule.params
let ruleSelector = getAtruleSelector(atRule, paramName)
let newRule = postcss.rule({
selector: ruleSelector
})
atRule.nodes.forEach((item) => {
if (item.type === 'decl') {
newRule.append(item)
}
})
css.append(newRule)
}
return function (css, result) {
let atRules = []
css.walkAtRules(function (atRule) {
atRules.push(atRule)
processAtrule(css, atRule)
})
atRule.forEach((item) => {
item.remove()
})
}
})