@@ -4,6 +4,7 @@ import template from 'babel-template';
44import traverse from 'babel-traverse' ;
55import { parse } from 'babylon' ;
66import resolveFrom from 'resolve-from' ;
7+
78import optimize from './optimize' ;
89import escapeBraces from './escapeBraces' ;
910import transformSvg from './transformSvg' ;
@@ -22,31 +23,46 @@ let ignoreRegex;
2223
2324export default ( { types : t } ) => ( {
2425 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+ } ,
2539 ImportDeclaration ( path , state ) {
40+ const importPath = path . node . source . value ;
2641 const { ignorePattern, caseSensitive, root, alias } = state . opts ;
27-
42+ const { file } = state ;
43+
2844 if ( ignorePattern ) {
2945 // Only set the ignoreRegex once:
3046 ignoreRegex = ignoreRegex || new RegExp ( ignorePattern ) ;
3147 // Test if we should ignore this:
32- if ( ignoreRegex . test ( path . node . source . value ) ) {
48+ if ( ignoreRegex . test ( importPath ) ) {
3349 return ;
3450 }
3551 }
3652 // This plugin only applies for SVGs:
37- if ( extname ( path . node . source . value ) === '.svg' ) {
53+ if ( extname ( importPath ) === '.svg' ) {
3854 // We only support the import default specifier, so let's use that identifier:
3955 const importIdentifier = path . node . specifiers [ 0 ] . local ;
40- const iconPath = state . file . opts . filename ;
56+ const iconPath = file . opts . filename ;
4157
42- const aliasMatch = alias [ path . node . source . value . split ( '/' ) [ 0 ] ] ;
58+ const aliasMatch = alias [ importPath . split ( '/' ) [ 0 ] ] ;
4359 let svgPath ;
4460 if ( aliasMatch ) {
4561 const resolveRoot = resolve ( process . cwd ( ) , root || './' ) ;
4662 const aliasedPath = resolve ( resolveRoot , aliasMatch ) ;
47- svgPath = aliasedPath + path . node . source . value . replace ( aliasMatch , '' ) ;
63+ svgPath = aliasedPath + importPath . replace ( aliasMatch , '' ) ;
4864 } else {
49- svgPath = resolveFrom ( dirname ( iconPath ) , path . node . source . value ) ;
65+ svgPath = resolveFrom ( dirname ( iconPath ) , importPath ) ;
5066 if ( caseSensitive && ! fileExistsWithCaseSync ( svgPath ) ) {
5167 throw new Error ( `File path didn't match case of file on disk: ${ svgPath } ` ) ;
5268 }
@@ -101,6 +117,7 @@ export default ({ types: t }) => ({
101117 const svgReplacement = buildSvg ( opts ) ;
102118 path . replaceWith ( svgReplacement ) ;
103119 }
120+ file . get ( 'ensureReact' ) ( ) ;
104121 }
105122 } ,
106123 } ,
0 commit comments