-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathcache-custom-properties.js
65 lines (56 loc) · 1.78 KB
/
cache-custom-properties.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
import * as fs from 'fs/promises';
import path from 'path';
import postcss from 'postcss';
import postcssCustomProperties from 'postcss-custom-properties';
import * as postCssValueParser from 'postcss-values-parser';
export const CacheCustomProperties = async masterCSSPath => {
const CSS_PATH = path.resolve(masterCSSPath);
try {
const fileData = { customProperties: {} };
const cssFile = await fs.readFile(CSS_PATH, 'utf8');
const postcssResult = await postcss([postcssCustomProperties()]).process(
cssFile,
{
from: CSS_PATH,
},
);
/**
* Walk through all the declarations and find the custom properties
* and their values. Store them in the fileData object.
*/
postcssResult.root.walkDecls(decl => {
if (decl.prop.startsWith('--')) {
fileData.customProperties[decl.prop] = decl.value;
}
});
/**
* Walk through all the custom properties and find the ones that
* have a single var() value. Replace the value with the value of
* the var() it references.
*/
for (const key in fileData.customProperties) {
const valueNode = postCssValueParser.parse(
fileData.customProperties[key],
);
const onlyVars = valueNode.nodes.filter(node => node.isVar);
if (onlyVars.length === 1) {
const keyToFind = onlyVars[0].params
.trim()
.substring(1, onlyVars[0].params.length - 1);
fileData.customProperties[key] = fileData.customProperties[keyToFind];
}
}
let json = JSON.stringify(fileData);
try {
await fs.writeFile(
'./custom-properties.module.js',
`export default ${json};`,
'utf8',
);
} catch (err) {
console.error(err);
}
} catch (err) {
console.error(err);
}
};