import * as babel from '@babel/core' ; import { NodePath } from '@babel/traverse' ; import { findImportStatement } from './import' ; type ImportDeclaration = babel . types . ImportDeclaration ; type MemberExpression = babel . types . MemberExpression ; type Program = babel . types . Program ; type Identifier = babel . types . Identifier ; const insertImportReact = ( program , specifier ) => { const expression = babel . types . importDeclaration ( [ babel . types . importSpecifier ( babel . types . identifier ( specifier ) , babel . types . identifier ( specifier ) ) , ] , babel . types . stringLiteral ( 'react' ) ) ; const [ inserted ] = program . unshiftContainer ( 'body' , expression ) ; return inserted ; } ; const constructCallee = ( importStatement , specifier ) => { const specifiers = importStatement . get ( 'specifiers' ) ; for ( const currentSpecifier of specifiers ) { if ( currentSpecifier . isImportNamespaceSpecifier ( ) ) { const name = currentSpecifier . get ( 'local' ) . node . name ; return babel . types . memberExpression ( babel . types . identifier ( name ) , babel . types . identifier ( specifier ) ) ; } else if ( currentSpecifier . isImportDefaultSpecifier ( ) ) { const name = currentSpecifier . get ( 'local' ) . node . name ; return babel . types . memberExpression ( babel . types . identifier ( name ) , babel . types . identifier ( specifier ) ) ; } else if ( currentSpecifier . isImportSpecifier ( ) ) { const name = currentSpecifier . get ( 'local' ) . node . name ; if ( name === specifier ) { return babel . types . identifier ( specifier ) ; } } } importStatement . pushContainer ( 'specifiers' , babel . types . importSpecifier ( babel . types . identifier ( specifier ) , babel . types . identifier ( specifier ) ) ) ; return babel . types . identifier ( specifier ) ; } ; export const prepareReactImport = ( program , specifier ) : Identifier | MemberExpression => { const importStatement = findImportStatement ( program , 'react' ) ?? insertImportReact ( program , specifier ) ; return constructCallee ( importStatement , specifier ) ; } ;