Skip to content

Commit be29be0

Browse files
refactor: url replacer logic (#828)
1 parent 9e52d26 commit be29be0

File tree

2 files changed

+19
-24
lines changed

2 files changed

+19
-24
lines changed

lib/loader.js

+11-23
Original file line numberDiff line numberDiff line change
@@ -213,39 +213,27 @@ module.exports = function loader(content, map) {
213213
placholderRegExps.urlItemG,
214214
(item) => {
215215
const match = placholderRegExps.urlItem.exec(item);
216-
let idx = Number(match[1]);
216+
const idx = Number(match[1]);
217217

218218
if (!urlItems[idx]) {
219219
return item;
220220
}
221221

222222
const urlItem = urlItems[idx];
223223
const { url } = urlItem;
224-
225-
idx = url.indexOf('?#');
226-
227-
if (idx < 0) {
228-
idx = url.indexOf('#');
229-
}
230-
231-
let urlRequest;
232-
233-
if (idx > 0) {
234-
// idx === 0 is catched by isUrlRequest
235-
// in cases like url('webfont.eot?#iefix')
236-
urlRequest = url.substr(0, idx);
237-
return `" + escape(require(${stringifyRequest(
238-
this,
239-
urlRequest
240-
)}) + "${url.substr(idx)}") + "`;
241-
}
242-
243-
urlRequest = url;
224+
// Remove `#hash` and `?#hash` from `require`
225+
const [normalizedUrl, singleQuery, hashValue] = url.split(/(\?)?#/);
226+
const hash =
227+
singleQuery || hashValue
228+
? `"${singleQuery ? '?' : ''}${
229+
hashValue ? `#${hashValue}` : ''
230+
}"`
231+
: '';
244232

245233
return `" + escape(require(${stringifyRequest(
246234
this,
247-
urlRequest
248-
)})) + "`;
235+
normalizedUrl
236+
)})${hash ? ` + ${hash}` : ''}) + "`;
249237
}
250238
);
251239
}

lib/plugins/postcss-url-parser.js

+8-1
Original file line numberDiff line numberDiff line change
@@ -82,13 +82,20 @@ function mapUrls(parsed, map) {
8282
});
8383
}
8484

85+
function uniq(array) {
86+
return array.reduce(
87+
(acc, d) => (acc.indexOf(d) === -1 ? [...acc, d] : acc),
88+
[]
89+
);
90+
}
91+
8592
module.exports = postcss.plugin(
8693
pluginName,
8794
(options) =>
8895
function process(css) {
8996
const urlItems = [];
9097
const traversed = walkDeclsWithUrl(css, (value) => isUrlRequest(value));
91-
const paths = flatten(traversed.map((item) => item.values));
98+
const paths = uniq(flatten(traversed.map((item) => item.values)));
9299

93100
if (paths.length === 0) {
94101
return;

0 commit comments

Comments
 (0)