1
1
use std:: mem;
2
2
3
- use swc_common:: collections:: AHashSet ;
3
+ use swc_common:: collections:: { AHashMap , AHashSet } ;
4
4
use swc_ecma_ast:: * ;
5
5
use swc_ecma_utils:: stack_size:: maybe_grow_default;
6
6
use swc_ecma_visit:: { noop_visit_type, Visit , VisitMut , VisitMutWith , VisitWith } ;
@@ -10,11 +10,15 @@ use crate::{strip_type::IsConcrete, ImportsNotUsedAsValues};
10
10
#[ derive( Debug , Default ) ]
11
11
struct UsageCollect {
12
12
id_usage : AHashSet < Id > ,
13
+ import_chain : AHashMap < Id , Id > ,
13
14
}
14
15
15
16
impl From < AHashSet < Id > > for UsageCollect {
16
17
fn from ( id_usage : AHashSet < Id > ) -> Self {
17
- Self { id_usage }
18
+ Self {
19
+ id_usage,
20
+ import_chain : Default :: default ( ) ,
21
+ }
18
22
}
19
23
}
20
24
@@ -68,7 +72,15 @@ impl Visit for UsageCollect {
68
72
return ;
69
73
} ;
70
74
71
- get_module_ident ( ts_entity_name) . visit_with ( self ) ;
75
+ let id = get_module_ident ( ts_entity_name) ;
76
+
77
+ if n. is_export {
78
+ id. visit_with ( self ) ;
79
+ n. id . visit_with ( self ) ;
80
+ return ;
81
+ }
82
+
83
+ self . import_chain . insert ( n. id . to_id ( ) , id. to_id ( ) ) ;
72
84
}
73
85
74
86
fn visit_export_named_specifier ( & mut self , n : & ExportNamedSpecifier ) {
@@ -101,6 +113,26 @@ impl UsageCollect {
101
113
fn has_usage ( & self , id : & Id ) -> bool {
102
114
self . id_usage . contains ( id)
103
115
}
116
+
117
+ fn analyze_import_chain ( & mut self ) {
118
+ if self . import_chain . is_empty ( ) {
119
+ return ;
120
+ }
121
+
122
+ let mut new_usage = AHashSet :: default ( ) ;
123
+ for id in & self . id_usage {
124
+ let mut entry = self . import_chain . remove_entry ( id) ;
125
+ while let Some ( ( id, next) ) = entry {
126
+ new_usage. insert ( next) ;
127
+ entry = self . import_chain . remove_entry ( & id) ;
128
+ }
129
+ if self . import_chain . is_empty ( ) {
130
+ break ;
131
+ }
132
+ }
133
+ self . import_chain . clear ( ) ;
134
+ self . id_usage . extend ( new_usage) ;
135
+ }
104
136
}
105
137
106
138
fn get_module_ident ( ts_entity_name : & TsEntityName ) -> & Ident {
@@ -264,6 +296,8 @@ impl VisitMut for StripImportExport {
264
296
n. visit_with ( & mut usage_info) ;
265
297
n. visit_with ( & mut declare_info) ;
266
298
299
+ usage_info. analyze_import_chain ( ) ;
300
+
267
301
let mut strip_ts_import_equals = StripTsImportEquals ;
268
302
269
303
n. retain_mut ( |module_item| match module_item {
0 commit comments