@@ -18,6 +18,7 @@ export interface StateContext {
1818 hash : string ;
1919 count : number ;
2020 imports : Map < string , t . Identifier > ;
21+ valid : boolean ;
2122
2223 definitions : {
2324 register : ImportDefinition ;
@@ -146,7 +147,12 @@ function traceBinding(path: babel.NodePath, name: string): Binding | undefined {
146147 if ( right ) {
147148 return traceBinding ( path , right . node . name ) ;
148149 }
149- return current ;
150+
151+ // Only valid for functions
152+ const func = unwrapPath ( current . path . get ( 'init' ) , isValidFunction ) ;
153+ if ( func ) {
154+ return current ;
155+ }
150156 }
151157 }
152158 return undefined ;
@@ -329,10 +335,16 @@ function transformModuleLevelDirective(ctx: StateContext, program: babel.NodePat
329335 }
330336 }
331337
332- program . pushContainer ( "body" , [
333- t . variableDeclaration ( "const" , declarations ) ,
334- t . exportNamedDeclaration ( null , specifiers , null ) ,
335- ] ) ;
338+ const body : t . Statement [ ] = [ ] ;
339+
340+ if ( declarations . length > 0 ) {
341+ body . push ( t . variableDeclaration ( "const" , declarations ) ) ;
342+ }
343+ if ( specifiers . length > 0 ) {
344+ body . push ( t . exportNamedDeclaration ( null , specifiers , null ) ) ;
345+ }
346+
347+ program . pushContainer ( "body" , body ) ;
336348 }
337349}
338350
@@ -344,6 +356,7 @@ export function directivesPlugin(): babel.PluginObj<State> {
344356 const isModuleLevel = isDirectiveValid ( ctx . opts , program . node . directives ) ;
345357 if ( isModuleLevel ) {
346358 transformModuleLevelDirective ( ctx . opts , program ) ;
359+ ctx . opts . valid = true ;
347360 } else {
348361 // First, bubble up function declarations
349362 program . traverse ( {
@@ -366,6 +379,7 @@ export function directivesPlugin(): babel.PluginObj<State> {
366379 program . scope . crawl ( ) ;
367380
368381 if ( ctx . opts . count > 0 ) {
382+ ctx . opts . valid = true ;
369383 removeUnusedVariables ( program ) ;
370384 }
371385 }
0 commit comments