@@ -4,6 +4,7 @@ import template from 'babel-template';
4
4
import traverse from 'babel-traverse' ;
5
5
import { parse } from 'babylon' ;
6
6
import resolveFrom from 'resolve-from' ;
7
+
7
8
import optimize from './optimize' ;
8
9
import escapeBraces from './escapeBraces' ;
9
10
import transformSvg from './transformSvg' ;
@@ -22,31 +23,46 @@ let ignoreRegex;
22
23
23
24
export default ( { types : t } ) => ( {
24
25
visitor : {
26
+ Program : {
27
+ enter ( { scope, node } , { file } ) {
28
+ if ( ! scope . hasBinding ( 'React' ) ) {
29
+ const reactImportDeclaration = t . importDeclaration ( [
30
+ t . importDefaultSpecifier ( t . identifier ( 'React' ) ) ,
31
+ ] , t . stringLiteral ( 'react' ) ) ;
32
+
33
+ file . set ( 'ensureReact' , ( ) => { node . body . unshift ( reactImportDeclaration ) ; } ) ;
34
+ } else {
35
+ file . set ( 'ensureReact' , ( ) => { } ) ;
36
+ }
37
+ } ,
38
+ } ,
25
39
ImportDeclaration ( path , state ) {
40
+ const importPath = path . node . source . value ;
26
41
const { ignorePattern, caseSensitive, root, alias } = state . opts ;
27
-
42
+ const { file } = state ;
43
+
28
44
if ( ignorePattern ) {
29
45
// Only set the ignoreRegex once:
30
46
ignoreRegex = ignoreRegex || new RegExp ( ignorePattern ) ;
31
47
// Test if we should ignore this:
32
- if ( ignoreRegex . test ( path . node . source . value ) ) {
48
+ if ( ignoreRegex . test ( importPath ) ) {
33
49
return ;
34
50
}
35
51
}
36
52
// This plugin only applies for SVGs:
37
- if ( extname ( path . node . source . value ) === '.svg' ) {
53
+ if ( extname ( importPath ) === '.svg' ) {
38
54
// We only support the import default specifier, so let's use that identifier:
39
55
const importIdentifier = path . node . specifiers [ 0 ] . local ;
40
- const iconPath = state . file . opts . filename ;
56
+ const iconPath = file . opts . filename ;
41
57
42
- const aliasMatch = alias [ path . node . source . value . split ( '/' ) [ 0 ] ] ;
58
+ const aliasMatch = alias [ importPath . split ( '/' ) [ 0 ] ] ;
43
59
let svgPath ;
44
60
if ( aliasMatch ) {
45
61
const resolveRoot = resolve ( process . cwd ( ) , root || './' ) ;
46
62
const aliasedPath = resolve ( resolveRoot , aliasMatch ) ;
47
- svgPath = aliasedPath + path . node . source . value . replace ( aliasMatch , '' ) ;
63
+ svgPath = aliasedPath + importPath . replace ( aliasMatch , '' ) ;
48
64
} else {
49
- svgPath = resolveFrom ( dirname ( iconPath ) , path . node . source . value ) ;
65
+ svgPath = resolveFrom ( dirname ( iconPath ) , importPath ) ;
50
66
if ( caseSensitive && ! fileExistsWithCaseSync ( svgPath ) ) {
51
67
throw new Error ( `File path didn't match case of file on disk: ${ svgPath } ` ) ;
52
68
}
@@ -101,6 +117,7 @@ export default ({ types: t }) => ({
101
117
const svgReplacement = buildSvg ( opts ) ;
102
118
path . replaceWith ( svgReplacement ) ;
103
119
}
120
+ file . get ( 'ensureReact' ) ( ) ;
104
121
}
105
122
} ,
106
123
} ,
0 commit comments