1
- import { extname , dirname , parse as parseFilename } from 'path' ;
2
- import { readFileSync } from 'fs' ;
1
+ import { extname , dirname , parse as parseFilename , resolve as resolvePath } from 'path' ;
2
+ import { readFileSync , existsSync } from 'fs' ;
3
3
import { parse } from '@babel/parser' ;
4
4
import { declare } from '@babel/helper-plugin-utils' ;
5
5
import resolve from 'resolve' ;
@@ -48,7 +48,7 @@ export default declare(({
48
48
if ( typeof importPath !== 'string' ) {
49
49
throw new TypeError ( '`applyPlugin` `importPath` must be a string' ) ;
50
50
}
51
- const { ignorePattern, caseSensitive, filename : providedFilename } = state . opts ;
51
+ const { ignorePattern, caseSensitive, filename : providedFilename , root , alias } = state . opts ;
52
52
const { file, filename } = state ;
53
53
if ( ignorePattern ) {
54
54
// Only set the ignoreRegex once:
@@ -61,14 +61,40 @@ export default declare(({
61
61
// This plugin only applies for SVGs:
62
62
if ( extname ( importPath ) === '.svg' ) {
63
63
const iconPath = filename || providedFilename ;
64
- const svgPath = resolve . sync ( importPath , { basedir : dirname ( iconPath ) } ) ;
65
- if ( caseSensitive && ! fileExistsWithCaseSync ( svgPath ) ) {
66
- throw new Error ( `File path didn't match case of file on disk: ${ svgPath } ` ) ;
64
+ const aliasPart = importPath . split ( '/' ) [ 0 ] ;
65
+ const aliasMatch = alias [ aliasPart ] ;
66
+ const svgPaths = [ ] ;
67
+ let chosenPath ;
68
+
69
+ if ( aliasMatch ) {
70
+ const resolveRoot = resolvePath ( process . cwd ( ) , root || './' ) ;
71
+ const aliasMatches = typeof aliasMatch === 'string' ? [ aliasMatch ] : aliasMatch ;
72
+
73
+ aliasMatches . forEach ( ( match ) => {
74
+ const aliasedPath = resolvePath ( resolveRoot , match ) ;
75
+ svgPaths . push ( resolvePath ( aliasedPath , importPath . replace ( `${ aliasPart } /` , '' ) ) ) ;
76
+ } ) ;
77
+ } else {
78
+ svgPaths . push ( resolve . sync ( importPath , { basedir : dirname ( iconPath ) } ) ) ;
67
79
}
68
- if ( ! svgPath ) {
80
+
81
+ for ( let i = 0 ; i < svgPaths . length ; i += 1 ) {
82
+ const svgPath = svgPaths [ i ] ;
83
+ if ( caseSensitive && ! fileExistsWithCaseSync ( svgPath ) ) {
84
+ throw new Error ( `File path didn't match case of file on disk: ${ svgPath } ` ) ;
85
+ }
86
+
87
+ if ( svgPath && existsSync ( svgPath ) ) {
88
+ chosenPath = svgPath ;
89
+ break ;
90
+ }
91
+ }
92
+
93
+ if ( ! chosenPath ) {
69
94
throw new Error ( `File path does not exist: ${ importPath } ` ) ;
70
95
}
71
- const rawSource = readFileSync ( svgPath , 'utf8' ) ;
96
+
97
+ const rawSource = readFileSync ( chosenPath , 'utf8' ) ;
72
98
const optimizedSource = state . opts . svgo === false
73
99
? rawSource
74
100
: optimize ( rawSource , state . opts . svgo ) ;
0 commit comments