@@ -22,31 +22,77 @@ export function adexLoader() {
22
22
treeShaking : true ,
23
23
} )
24
24
25
- const ast = parse ( transformResult . code , {
26
- sourceType : 'module' ,
25
+ const ast = moduleParser ( transformResult . code )
26
+ const astWithoutLoader = removeLoaderFromAST ( ast )
27
+ const astWithoutImports = removeUnusedImports ( astWithoutLoader )
28
+ console . log ( {
29
+ ast,
30
+ astWithoutLoader,
31
+ astWithoutImports,
27
32
} )
28
33
29
- traverse ( ast , {
30
- Identifier ( path ) {
31
- if ( path . node . name !== 'loader' ) return
34
+ return generate ( astWithoutImports )
35
+ } ,
36
+ }
37
+ }
32
38
33
- if ( path . parent ) {
34
- if ( path . parent . type === 'ExportSpecifier' ) {
35
- path . parentPath . remove ( )
36
- }
39
+ function moduleParser ( source ) {
40
+ return parse ( source , {
41
+ sourceType : 'module' ,
42
+ } )
43
+ }
37
44
38
- if ( path . parentPath . parentPath ) {
39
- if (
40
- path . parentPath . parentPath . node . type === 'VariableDeclaration'
41
- ) {
42
- path . parentPath . parentPath . remove ( )
43
- }
44
- }
45
+ function removeLoaderFromAST ( ast ) {
46
+ traverse ( ast , {
47
+ Identifier ( path ) {
48
+ if ( path . node . name !== 'loader' ) return
49
+
50
+ if ( path . parent ) {
51
+ if ( path . parent . type === 'ExportSpecifier' ) {
52
+ path . parentPath . remove ( )
53
+ }
54
+
55
+ if ( path . parentPath . parentPath ) {
56
+ if ( path . parentPath . parentPath . node . type === 'VariableDeclaration' ) {
57
+ path . parentPath . parentPath . remove ( )
45
58
}
46
- } ,
47
- } )
59
+ }
60
+ }
61
+ } ,
62
+ } )
63
+ return moduleParser ( generate ( ast ) . code )
64
+ }
65
+
66
+ function removeUnusedImports ( ast ) {
67
+ const paths = new Map ( )
48
68
49
- return generate ( ast )
69
+ const visitor = {
70
+ ImportSpecifier ( path ) {
71
+ paths . set ( path . node . local . name , path )
72
+ } ,
73
+ ImportDefaultSpecifier ( path ) {
74
+ paths . set ( path . node . local . name , path )
75
+ } ,
76
+ Program : {
77
+ exit ( path ) {
78
+ for ( let [ key , path ] of paths . entries ( ) ) {
79
+ const binding = path . scope . bindings [ key ]
80
+ if ( ! binding ) continue
81
+ if ( binding . references !== 0 ) continue
82
+ if ( path . node . type == 'ImportDefaultSpecifier' ) {
83
+ path . parentPath . remove ( )
84
+ } else {
85
+ if ( path . parent . specifiers . length === 1 ) {
86
+ path . parentPath . remove ( )
87
+ } else {
88
+ path . remove ( )
89
+ }
90
+ }
91
+ }
92
+ } ,
50
93
} ,
51
94
}
95
+
96
+ traverse ( ast , visitor )
97
+ return moduleParser ( generate ( ast ) . code )
52
98
}
0 commit comments