1
1
const postcss = require ( 'postcss' ) ;
2
+ const valueParser = require ( 'postcss-value-parser' ) ;
2
3
const loaderUtils = require ( 'loader-utils' ) ;
3
- const Tokenizer = require ( 'css-selector-tokenizer' ) ;
4
4
5
5
const pluginName = 'postcss-import-parser' ;
6
6
7
+ function getArg ( nodes ) {
8
+ return nodes . length !== 0 && nodes [ 0 ] . type === 'string'
9
+ ? nodes [ 0 ] . value
10
+ : valueParser . stringify ( nodes ) ;
11
+ }
12
+
13
+ function getUrl ( node ) {
14
+ if ( node . type === 'function' && node . value . toLowerCase ( ) === 'url' ) {
15
+ return getArg ( node . nodes ) ;
16
+ }
17
+
18
+ if ( node . type === 'string' ) {
19
+ return node . value ;
20
+ }
21
+
22
+ return '' ;
23
+ }
24
+
25
+ function parseImport ( params ) {
26
+ const { nodes } = valueParser ( params ) ;
27
+
28
+ if ( nodes . length === 0 ) {
29
+ return null ;
30
+ }
31
+
32
+ const url = getUrl ( nodes [ 0 ] ) ;
33
+
34
+ if ( url . trim ( ) . length === 0 ) {
35
+ return null ;
36
+ }
37
+
38
+ return {
39
+ url,
40
+ media : valueParser . stringify ( nodes . slice ( 1 ) ) . trim ( ) ,
41
+ } ;
42
+ }
43
+
7
44
module . exports = postcss . plugin (
8
45
pluginName ,
9
46
( options ) =>
@@ -25,43 +62,22 @@ module.exports = postcss.plugin(
25
62
return ;
26
63
}
27
64
28
- const values = Tokenizer . parseValues ( atrule . params ) ;
29
- let [ url ] = values . nodes [ 0 ] . nodes ;
65
+ const parsed = parseImport ( atrule . params ) ;
30
66
31
- if ( url && url . type === 'url' ) {
32
- ( { url } = url ) ;
33
- } else if ( url && url . type === 'string' ) {
34
- url = url . value ;
35
- } else {
36
- result . warn ( `Unable to find uri in '${ atrule . toString ( ) } '` , {
67
+ if ( ! parsed ) {
68
+ // eslint-disable-next-line consistent-return
69
+ return result . warn ( `Unable to find uri in '${ atrule . toString ( ) } '` , {
37
70
node : atrule ,
38
71
} ) ;
39
-
40
- return ;
41
72
}
42
73
43
- if ( ! url . replace ( / \s / g, '' ) . length ) {
44
- result . warn ( `Unable to find uri in '${ atrule . toString ( ) } '` , {
45
- node : atrule ,
46
- } ) ;
47
-
48
- return ;
49
- }
50
-
51
- values . nodes [ 0 ] . nodes . shift ( ) ;
52
-
53
- const mediaQuery = Tokenizer . stringifyValues ( values ) ;
54
-
55
- url = url . trim ( ) ;
74
+ let { url } = parsed ;
56
75
57
76
if ( loaderUtils . isUrlRequest ( url ) ) {
58
77
url = loaderUtils . urlToRequest ( url ) ;
59
78
}
60
79
61
- importItems . push ( {
62
- url,
63
- mediaQuery,
64
- } ) ;
80
+ importItems . push ( { url, mediaQuery : parsed . media } ) ;
65
81
66
82
atrule . remove ( ) ;
67
83
} ) ;
0 commit comments