-
-
Notifications
You must be signed in to change notification settings - Fork 608
/
Copy pathpostcss-icss-parser.js
89 lines (73 loc) · 2.44 KB
/
postcss-icss-parser.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
88
89
import postcss from 'postcss';
import { extractICSS, replaceValueSymbols, replaceSymbols } from 'icss-utils';
import { urlToRequest } from 'loader-utils';
const pluginName = 'postcss-icss-parser';
function normalizeIcssImports(icssImports) {
return Object.keys(icssImports).reduce((accumulator, url) => {
const tokensMap = icssImports[url];
const tokens = Object.keys(tokensMap);
if (tokens.length === 0) {
return accumulator;
}
const normalizedUrl = urlToRequest(url);
if (!accumulator[normalizedUrl]) {
// eslint-disable-next-line no-param-reassign
accumulator[normalizedUrl] = tokensMap;
} else {
// eslint-disable-next-line no-param-reassign
accumulator[normalizedUrl] = {
...accumulator[normalizedUrl],
...tokensMap,
};
}
return accumulator;
}, {});
}
export default postcss.plugin(
pluginName,
() =>
function process(css, result) {
const importReplacements = Object.create(null);
const { icssImports, icssExports } = extractICSS(css);
const normalizedIcssImports = normalizeIcssImports(icssImports);
Object.keys(normalizedIcssImports).forEach((url, importIndex) => {
const importName = `___CSS_LOADER_ICSS_IMPORT_${importIndex}___`;
result.messages.push({
pluginName,
type: 'import',
value: { type: 'icss-import', importName, url },
});
const tokenMap = normalizedIcssImports[url];
const tokens = Object.keys(tokenMap);
tokens.forEach((token, replacementIndex) => {
const replacementName = `___CSS_LOADER_ICSS_IMPORT_${importIndex}_REPLACEMENT_${replacementIndex}___`;
const localName = tokenMap[token];
importReplacements[token] = replacementName;
result.messages.push({
pluginName,
type: 'replacer',
value: {
type: 'icss-import',
importName,
replacementName,
localName,
},
});
});
});
if (Object.keys(importReplacements).length > 0) {
replaceSymbols(css, importReplacements);
}
Object.keys(icssExports).forEach((name) => {
const value = replaceValueSymbols(
icssExports[name],
importReplacements
);
result.messages.push({
pluginName,
type: 'export',
value: { name, value },
});
});
}
);