Skip to content

Commit f7e0739

Browse files
committed
Implement the rewriteCssUrls function.
1 parent cd8a29b commit f7e0739

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

index.js

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
'use strict';
2+
3+
module.exports = rewriteCssUrls;
4+
5+
//////////////////////////////
6+
7+
/**
8+
* Rewrite the urls in a css using the provided function.
9+
*
10+
* @param css
11+
* @param fn
12+
* @returns {*}
13+
*/
14+
function rewriteCssUrls(css, fn) {
15+
var replacePairs = replacePairsForResources(css, fn).concat(replacePairsForImports(css, fn));
16+
replacePairs.forEach(function(replacePair) {
17+
css = css.replace(replacePair[0], replacePair[1]);
18+
});
19+
20+
return css;
21+
}
22+
23+
/**
24+
* Find the replace pairs for @import tags without the `url()` tag.
25+
*
26+
* @param css
27+
* @param fn
28+
* @returns {Array}
29+
*/
30+
function replacePairsForImports(css, fn) {
31+
var matches = css.match(/@import(\s+)('|")(.+?)('|")/ig) || [];
32+
return matches.map(function(match) {
33+
var url = match.replace(/@import|'|"/gi, '').trim();
34+
return [match, '@import url("' + fn(url) + '")'];
35+
});
36+
}
37+
38+
/**
39+
* Find the replace pairs for resources using the `url()` tag.
40+
*
41+
* @param css
42+
* @param fn
43+
* @returns {Array}
44+
*/
45+
function replacePairsForResources(css, fn) {
46+
var matches = css.match(/url\(.+?\)/ig) || [];
47+
return matches.map(function(match) {
48+
var url = match.replace(/url\(|\)|'|"/gi, '').trim();
49+
return [match, 'url("' + fn(url) + '")'];
50+
});
51+
}

0 commit comments

Comments
 (0)