33 Author Tobias Koppers @sokra
44*/
55var csso = require ( "csso" ) ;
6+ var uriRegExp = / % C S S U R L \[ % ( .* ) % \] C S S U R L % / g;
67module . exports = function ( content ) {
7- var options = this ;
8+ var isRequireUrl = ! this || ! this . options || ! this . options . css ||
9+ typeof this . options . css . requireUrl === "string" ;
10+ var requireUrl = this && this . options && this . options . css &&
11+ this . options . css . requireUrl ||
12+ "file/auto!" ;
813 var result = [ ] ;
914 var tree = csso . parse ( content , "stylesheet" ) ;
10- if ( options . minimize )
15+ if ( this && this . minimize )
1116 tree = csso . compress ( tree ) ;
1217 tree = csso . cleanInfo ( tree ) ;
13-
18+
1419 var imports = extractImports ( tree ) ;
15-
20+ if ( isRequireUrl )
21+ annotateUrls ( tree ) ;
22+
1623 imports . forEach ( function ( imp ) {
1724 if ( imp . media . length > 0 ) {
18- result . push ( JSON . stringify ( "@media " + imp . media . join ( "" ) + "{" ) ) ;
25+ result . push ( JSON . stringify ( "@media( " + imp . media . join ( "" ) + ") {" ) ) ;
1926 }
20- result . push ( "require(" + JSON . stringify ( __filename ) + " + \"!\ " + " + JSON . stringify ( urlToRequire ( imp . url ) ) + ")" ) ;
27+ result . push ( "require(" + JSON . stringify ( __filename + "! " + urlToRequire ( imp . url ) ) + ")" ) ;
2128 if ( imp . media . length > 0 ) {
2229 result . push ( JSON . stringify ( "}" ) ) ;
2330 }
2431 } ) ;
25-
26- result . push ( JSON . stringify ( csso . translate ( tree ) ) ) ;
32+
33+ var css = JSON . stringify ( csso . translate ( tree ) ) ;
34+ if ( isRequireUrl ) {
35+ css = css . replace ( uriRegExp , function ( match ) {
36+ match = uriRegExp . exec ( match ) ;
37+ var url = JSON . parse ( "\"" + match [ 1 ] + "\"" ) ;
38+ return "\"+require(" + JSON . stringify ( requireUrl + urlToRequire ( url ) ) + ")+\"" ;
39+ } ) ;
40+
41+ }
42+ result . push ( css ) ;
2743 return "module.exports =\n\t" + result . join ( " +\n\t" ) + ";" ;
2844}
2945
@@ -71,4 +87,31 @@ function extractImports(tree) {
7187 tree . splice ( i , 1 ) ;
7288 } ) ;
7389 return results ;
90+ }
91+ function annotateUrls ( tree ) {
92+ function iterateChildren ( ) {
93+ for ( var i = 1 ; i < tree . length ; i ++ ) {
94+ annotateUrls ( tree [ i ] ) ;
95+ }
96+ }
97+ switch ( tree [ 0 ] ) {
98+ case "stylesheet" : return iterateChildren ( ) ;
99+ case "ruleset" : return iterateChildren ( ) ;
100+ case "block" : return iterateChildren ( ) ;
101+ case "declaration" : return iterateChildren ( ) ;
102+ case "value" : return iterateChildren ( ) ;
103+ case "uri" :
104+ for ( var i = 1 ; i < tree . length ; i ++ ) {
105+ var item = tree [ i ] ;
106+ switch ( item [ 0 ] ) {
107+ case "ident" :
108+ case "raw" :
109+ item [ 1 ] = "%CSSURL[%" + item [ 1 ] + "%]CSSURL%" ;
110+ return ;
111+ case "string" :
112+ item [ 1 ] = "%CSSURL[%" + item [ 1 ] . substring ( 1 , item [ 1 ] . length - 1 ) + "%]CSSURL%" ;
113+ return ;
114+ }
115+ }
116+ }
74117}
0 commit comments