-
-
Notifications
You must be signed in to change notification settings - Fork 608
/
Copy pathpostcss-icss-parser.js
95 lines (77 loc) · 2.65 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
90
91
92
93
94
95
import postcss from 'postcss';
import { extractICSS, replaceValueSymbols, replaceSymbols } from 'icss-utils';
import { normalizeUrl, resolveRequests, requestify } from '../utils';
export default postcss.plugin(
'postcss-icss-parser',
(options) => async (css, result) => {
const importReplacements = Object.create(null);
const { icssImports, icssExports } = extractICSS(css);
const imports = new Map();
const tasks = [];
// eslint-disable-next-line guard-for-in
for (const url in icssImports) {
const tokens = icssImports[url];
if (Object.keys(tokens).length === 0) {
// eslint-disable-next-line no-continue
continue;
}
const request = requestify(normalizeUrl(url, true), options.rootContext);
const doResolve = async () => {
const { resolver, context } = options;
const resolvedUrl = await resolveRequests(resolver, context, [
...new Set([url, request]),
]);
return { url: resolvedUrl, tokens };
};
tasks.push(doResolve());
}
const results = await Promise.all(tasks);
for (let index = 0; index <= results.length - 1; index++) {
const { url, tokens } = results[index];
const importKey = url;
let importName = imports.get(importKey);
if (!importName) {
importName = `___CSS_LOADER_ICSS_IMPORT_${imports.size}___`;
imports.set(importKey, importName);
result.messages.push(
{
type: 'import',
value: {
importName,
url: options.urlHandler(url),
icss: true,
order: 0,
index,
},
},
{
type: 'api-import',
value: {
type: 'internal',
importName,
dedupe: true,
order: 0,
index,
},
}
);
}
for (const [replacementIndex, token] of Object.keys(tokens).entries()) {
const replacementName = `___CSS_LOADER_ICSS_IMPORT_${index}_REPLACEMENT_${replacementIndex}___`;
const localName = tokens[token];
importReplacements[token] = replacementName;
result.messages.push({
type: 'replacement',
value: { type: 'icss', replacementName, importName, localName },
});
}
}
if (Object.keys(importReplacements).length > 0) {
replaceSymbols(css, importReplacements);
}
for (const name of Object.keys(icssExports)) {
const value = replaceValueSymbols(icssExports[name], importReplacements);
result.messages.push({ type: 'export', value: { name, value } });
}
}
);