-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
80 lines (70 loc) · 2.19 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
70
71
72
73
74
75
76
77
78
79
80
// postcss-mpvuew-wxss.js
// https://github.com/postcss/postcss/blob/master/docs/writing-a-plugin.md
const postcss = require('postcss');
const selectorParser = require('postcss-selector-parser');
const replaceTagSelector = require('./lib/wxmlTagMap');
const { isRegExp } = require('./lib/utils');
const defConfig = {
cleanSelector: ['*'],
cleanAtRule: [{
name: 'media',
params: ['print']
}],
remToRpx: 100,
replaceTagSelector
};
const remReg = /(\d*\.?\d+)rem/ig;
const replaceRemOption = { fast: 'rem' };
module.exports = postcss.plugin('postcss-mpvue-wxss', function (options) {
// Work with options here
options = Object.assign({}, defConfig, options);
return function (root) {
// Transform CSS AST here: root, result
root.walkAtRules(rule => {
// 清理不支持的@开头规则
for (cleanRule of options.cleanAtRule) {
if (cleanRule.name !== rule.name) {
continue;
}
if (!cleanRule.params) {
return rule.remove();
}
for (param of cleanRule.params) {
if (isRegExp(param) && param.test(rule.params) || param === rule.params) {
return rule.remove();
}
}
}
});
root.walkRules(rule => {
const { selector } = rule || {};
// rem 转换 rpx
rule.replaceValues(remReg, replaceRemOption, str => {
return options.remToRpx * parseFloat(str) + 'rpx';
});
rule.selector = selectorParser(function (selectors) {
selectors.each(function (selector) {
selector.each(function (n) {
// 转换 tag 选择器
if (n.type === 'tag') {
const k = n.value;
const v = options.replaceTagSelector[k];
if (v) {
n.value = v === 'replaceToClass' ? `._${k}` : v;
}
}
// 清理不支持的选择器
if (options.cleanSelector.includes(n.value)) {
// return n.value = 'view';
return rule.remove();
}
})
})
}).process(selector).result;
});
// 清理所有的注释
root.walkComments(comment => {
comment.remove();
});
};
});