File tree 1 file changed +51
-0
lines changed
1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
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 ( / @ i m p o r t ( \s + ) ( ' | " ) ( .+ ?) ( ' | " ) / ig) || [ ] ;
32
+ return matches . map ( function ( match ) {
33
+ var url = match . replace ( / @ i m p o r t | ' | " / 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 ( / u r l \( .+ ?\) / ig) || [ ] ;
47
+ return matches . map ( function ( match ) {
48
+ var url = match . replace ( / u r l \( | \) | ' | " / gi, '' ) . trim ( ) ;
49
+ return [ match , 'url("' + fn ( url ) + '")' ] ;
50
+ } ) ;
51
+ }
You can’t perform that action at this time.
0 commit comments