Skip to content

refactor: url replacer logic #828

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 30, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 11 additions & 23 deletions lib/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -213,39 +213,27 @@ 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;
}

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}` : ''}) + "`;
}
);
}
Expand Down
9 changes: 8 additions & 1 deletion lib/plugins/postcss-url-parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down