diff --git a/lib/loader.js b/lib/loader.js index b6bca865..b64a7709 100644 --- a/lib/loader.js +++ b/lib/loader.js @@ -213,7 +213,7 @@ module.exports = function loader(content, map) { placholderRegExps.urlItemG, (item) => { const match = placholderRegExps.urlItem.exec(item); - let idx = Number(match[1]); + const idx = Number(match[1]); if (!urlItems[idx]) { return item; @@ -221,31 +221,19 @@ module.exports = function loader(content, map) { const urlItem = urlItems[idx]; const { url } = urlItem; - - idx = url.indexOf('?#'); - - if (idx < 0) { - idx = url.indexOf('#'); - } - - let urlRequest; - - if (idx > 0) { - // idx === 0 is catched by isUrlRequest - // in cases like url('webfont.eot?#iefix') - urlRequest = url.substr(0, idx); - return `" + escape(require(${stringifyRequest( - this, - urlRequest - )}) + "${url.substr(idx)}") + "`; - } - - urlRequest = url; + // Remove `#hash` and `?#hash` from `require` + const [normalizedUrl, singleQuery, hashValue] = url.split(/(\?)?#/); + const hash = + singleQuery || hashValue + ? `"${singleQuery ? '?' : ''}${ + hashValue ? `#${hashValue}` : '' + }"` + : ''; return `" + escape(require(${stringifyRequest( this, - urlRequest - )})) + "`; + normalizedUrl + )})${hash ? ` + ${hash}` : ''}) + "`; } ); } diff --git a/lib/plugins/postcss-url-parser.js b/lib/plugins/postcss-url-parser.js index 004b986b..be137eaf 100644 --- a/lib/plugins/postcss-url-parser.js +++ b/lib/plugins/postcss-url-parser.js @@ -82,13 +82,20 @@ function mapUrls(parsed, map) { }); } +function uniq(array) { + return array.reduce( + (acc, d) => (acc.indexOf(d) === -1 ? [...acc, d] : acc), + [] + ); +} + module.exports = postcss.plugin( pluginName, (options) => function process(css) { const urlItems = []; const traversed = walkDeclsWithUrl(css, (value) => isUrlRequest(value)); - const paths = flatten(traversed.map((item) => item.values)); + const paths = uniq(flatten(traversed.map((item) => item.values))); if (paths.length === 0) { return;