-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathpostcss-remove-global.ts
More file actions
46 lines (41 loc) · 1.45 KB
/
Copy pathpostcss-remove-global.ts
File metadata and controls
46 lines (41 loc) · 1.45 KB
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
import type { Plugin } from 'postcss';
const pluginName = 'postcss-remove-global';
function removeGlobalPlugin(): Plugin {
return {
postcssPlugin: pluginName,
Once(root, helpers) {
const file = helpers.result.opts.from || '';
const isModule = /\.module\.(css|scss|sass)$/i.test(file);
if (isModule) {
return;
}
// :global in rules
root.walkRules((rule) => {
// :global as nested selector
const globalReg = /:global(\s+)/g;
// :global(.selector) as nested selector
const globalWithSelectorReg = /:global\(\s*((?:[a-zA-Z0-9.#:[\]_\-\s>+~]+))\s*\)/g;
if (rule.selector === ':global') {
const parent = rule.parent || root;
parent.append(...rule.nodes);
rule.remove();
} else if (rule.selector.match(globalReg)) {
rule.selector = rule.selector.replace(globalReg, '');
} else if (rule.selector.match(globalWithSelectorReg)) {
rule.selector = rule.selector.replace(globalWithSelectorReg, '$1');
}
});
// :global in AtRules
root.walkAtRules((atRule) => {
const name = atRule.name;
const params = atRule.params;
const globalReg = /:global\((\w+)\)/;
if (name === 'keyframes' && params.match(globalReg)) {
atRule.params = params.replace(globalReg, '$1');
}
});
},
};
}
removeGlobalPlugin.postcss = true;
export default removeGlobalPlugin;