-
-
Notifications
You must be signed in to change notification settings - Fork 608
/
Copy pathpostcss-url-parser.js
128 lines (98 loc) · 2.67 KB
/
postcss-url-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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
const postcss = require('postcss');
const valueParser = require('postcss-value-parser');
const pluginName = 'postcss-url-parser';
function walkUrls(parsed, callback) {
parsed.walk((node) => {
if (node.type !== 'function' || node.value.toLowerCase() !== 'url') {
return;
}
const url =
node.nodes.length !== 0 && node.nodes[0].type === 'string'
? node.nodes[0].value
: valueParser.stringify(node.nodes);
/* eslint-disable */
node.before = '';
node.after = '';
/* eslint-enable */
callback(node, url);
// Do not traverse inside url
// eslint-disable-next-line consistent-return
return false;
});
}
function filterUrls(parsed, result, decl, filter) {
const urls = [];
walkUrls(parsed, (node, url) => {
if (url.trim().replace(/\\[\r\n]/g, '').length === 0) {
result.warn(`Unable to find uri in '${decl.toString()}'`, {
node: decl,
});
return;
}
if (!filter(url)) {
return;
}
urls.push(url);
});
return urls;
}
function walkDeclsWithUrl(css, result, filter) {
const items = [];
css.walkDecls((decl) => {
if (!/url\(/i.test(decl.value)) {
return;
}
const parsed = valueParser(decl.value);
const values = filterUrls(parsed, result, decl, filter);
if (values.length === 0) {
return;
}
items.push({ decl, parsed, values });
});
return items;
}
function flatten(array) {
return array.reduce((acc, d) => [...acc, ...d], []);
}
function mapUrls(parsed, map) {
walkUrls(parsed, (node, content) => {
const placeholder = map(content);
if (!placeholder) {
return;
}
// eslint-disable-next-line no-param-reassign
node.nodes = [{ type: 'word', value: map(content) }];
});
}
function uniq(array) {
return array.reduce(
(acc, d) => (acc.indexOf(d) === -1 ? [...acc, d] : acc),
[]
);
}
module.exports = postcss.plugin(
pluginName,
(options) =>
function process(css, result) {
const traversed = walkDeclsWithUrl(css, result, options.filter);
const paths = uniq(flatten(traversed.map((item) => item.values)));
if (paths.length === 0) {
return;
}
const urls = {};
paths.forEach((path, index) => {
const placeholder = `___CSS_LOADER_URL___${index}___`;
urls[path] = placeholder;
result.messages.push({
pluginName,
type: 'url',
item: { url: path, placeholder },
});
});
traversed.forEach((item) => {
mapUrls(item.parsed, (value) => urls[value]);
// eslint-disable-next-line no-param-reassign
item.decl.value = item.parsed.toString();
});
}
);