-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathpostcss-property-to-custom-prop.js
More file actions
61 lines (54 loc) · 1.88 KB
/
postcss-property-to-custom-prop.js
File metadata and controls
61 lines (54 loc) · 1.88 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
* Tailwind 4 uses @property but these don't work inside shadow DOM
*
* See: https://github.com/tailwindlabs/tailwindcss/issues/15005
*
* This script converts @property rules to custom properties on :root, :host
*
* Courtesy of https://github.com/tailwindlabs/tailwindcss/discussions/16772#discussioncomment-12309978
*/
export function propertyToCustomProp() {
return {
postcssPlugin: 'postcss-property-to-custom-prop',
prepare() {
// Store all the properties we find
const properties = [];
return {
AtRule: {
property: (rule) => {
// Extract the property name and initial value
const propertyName = rule.params.match(/--[\w-]+/)?.[0];
let initialValue = '';
rule.walkDecls('initial-value', (decl) => {
initialValue = decl.value;
});
if (propertyName && initialValue) {
// Store the property
properties.push({ name: propertyName, value: initialValue });
// Remove the original @property rule
rule.remove();
}
},
},
OnceExit(root, { Rule, Declaration }) {
// If we found properties, add them to :root, :host
if (properties.length > 0) {
// Create the :root, :host rule using the Rule constructor from helpers
const rootRule = new Rule({ selector: ':root, :host' });
// Add all properties as declarations
properties.forEach((prop) => {
// Create a new declaration for each property
const decl = new Declaration({
prop: prop.name,
value: prop.value,
});
rootRule.append(decl);
});
// Add the rule to the beginning of the CSS
root.prepend(rootRule);
}
},
};
},
};
}