-
-
Notifications
You must be signed in to change notification settings - Fork 608
/
Copy pathpostcss-icss-parser.js
73 lines (60 loc) · 2.14 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
const postcss = require('postcss');
const valueParser = require('postcss-value-parser');
const icssUtils = require('icss-utils');
const loaderUtils = require('loader-utils');
const pluginName = 'postcss-icss-parser';
module.exports = postcss.plugin(
pluginName,
(options) =>
function process(css) {
const importItems = options.importItems || [];
const urlItems = options.urlItems || [];
const imports = {};
const icss = icssUtils.extractICSS(css);
const exports = icss.icssExports;
Object.keys(icss.icssImports).forEach((key) => {
const url = loaderUtils.parseString(key);
Object.keys(icss.icssImports[key]).forEach((prop) => {
imports[`$${prop}`] = importItems.length;
importItems.push({
url,
export: icss.icssImports[key][prop],
});
});
});
function replaceImportsInString(str) {
const tokens = valueParser(str);
tokens.walk((node) => {
if (node.type !== 'word') {
return;
}
const token = node.value;
const importIndex = imports[`$${token}`];
if (typeof importIndex === 'number') {
// eslint-disable-next-line no-param-reassign
node.value = `___CSS_LOADER_IMPORT___${importIndex}___`;
}
});
return tokens.toString();
}
// Replace tokens in declarations
css.walkDecls((decl) => {
// eslint-disable-next-line no-param-reassign
decl.value = replaceImportsInString(decl.value.toString());
});
// Replace tokens in at-rules
css.walkAtRules((atrule) => {
// eslint-disable-next-line no-param-reassign
atrule.params = replaceImportsInString(atrule.params.toString());
});
// Replace tokens in export
Object.keys(exports).forEach((exportName) => {
exports[exportName] = replaceImportsInString(exports[exportName]);
});
/* eslint-disable no-param-reassign */
options.importItems = importItems;
options.urlItems = urlItems;
options.exports = exports;
/* eslint-enable no-param-reassign */
}
);