-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
87 lines (84 loc) · 3.18 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
81
82
83
84
85
86
87
const config = require('./config');
module.exports = (opts = {}) => {
opts = { ...config, ...opts };
const covertRules = opts.unitGroup[opts.platform].map((item) => {
const rule = item.split('2');
if (rule[0] && rule[1]) {
return {
key: rule[0],
covert: rule[1]
};
}
});
const isRegExp = (val) => {
return typeof val === 'object' && val instanceof RegExp;
};
const isUnitIgnoreSelector =
opts.unitIgnore && Array.isArray(opts.unitIgnore.selector) && opts.unitIgnore.selector.length > 0;
const isUnitIgnoreProp = opts.unitIgnore && Array.isArray(opts.unitIgnore.prop) && opts.unitIgnore.prop.length > 0;
const isUnitIgnoreValue = opts.unitIgnore && Array.isArray(opts.unitIgnore.value) && opts.unitIgnore.value.length > 0;
const isSelectorRules = opts.selectorRules && Array.isArray(opts.selectorRules) && opts.selectorRules.length > 0;
// Work with options here
return {
postcssPlugin: 'postcss-uniapp-tailwindcss',
Rule(rule, postcss) {
// Transform CSS AST here
if (isSelectorRules) {
opts.selectorRules.forEach((item) => {
if (
(typeof item.pattern === 'string' && rule.selector === item.pattern) ||
(isRegExp(item.pattern) && item.pattern.test(rule.selector))
) {
rule.selector = rule.selector.replace(item.pattern, item.replacement);
}
});
}
},
Once(root, postcss) {
root.walkDecls((decl) => {
covertRules.forEach((item) => {
const times = opts.units[`${item.key}2${item.covert}`];
if (!times || typeof times !== 'number') {
return;
}
if (isUnitIgnoreSelector) {
const selector = decl.parent.selector;
const isIgnoreSelector = opts.unitIgnore.selector.some((item) => {
return (typeof item === 'string' && item === selector) || (isRegExp(item) && item.test(selector));
});
if (isIgnoreSelector) {
return;
}
}
if (isUnitIgnoreProp) {
const isIgnoreProp = opts.unitIgnore.prop.some((item) => {
return (typeof item === 'string' && item === decl.prop) || (isRegExp(item) && item.test(decl.prop));
});
if (isIgnoreProp) {
return;
}
}
const regExp = new RegExp(`([\\d\\.]+)${item.key}`, 'ig');
if (regExp.test(decl.value)) {
const match = decl.value.match(regExp);
match.forEach((matchItem) => {
let val = matchItem.toLowerCase();
if (isUnitIgnoreValue) {
const isIgnoreValue = opts.unitIgnore.value.some((item) => {
return (typeof item === 'string' && item.toLowerCase() === val) || (isRegExp(item) && item.test(val));
});
if (isIgnoreValue) {
return;
}
}
val = val.replace(item.key, '');
const newVal = `${val * times}${item.covert}`;
decl.value = decl.value.replace(matchItem, newVal);
});
}
});
});
}
};
};
module.exports.postcss = true;