@@ -76,12 +76,48 @@ module.exports = function (babel) {
76
76
// Extract import declarations and track imported identifiers
77
77
const imports = [ ] ;
78
78
const importedIdentifiers = new Set ( ) ;
79
+
80
+ const convertRequireIntoImportStatement = ( declaration ) => {
81
+ const moduleName = declaration . init . arguments [ 0 ] . value ;
82
+ if ( t . isIdentifier ( declaration . id ) ) {
83
+ // Case for `const fs = require("fs")`
84
+ return t . importDeclaration (
85
+ [ t . importDefaultSpecifier ( declaration . id ) ] ,
86
+ t . stringLiteral ( moduleName )
87
+ ) ;
88
+ } else if ( t . isObjectPattern ( declaration . id ) ) {
89
+ // Case for `const { parse } = require("module")`
90
+ const importSpecifiers = declaration . id . properties . map ( ( property ) =>
91
+ t . importSpecifier ( property . value , property . key )
92
+ ) ;
93
+ return t . importDeclaration (
94
+ importSpecifiers ,
95
+ t . stringLiteral ( moduleName )
96
+ ) ;
97
+ }
98
+ } ;
99
+
79
100
ast . program . body . forEach ( ( node ) => {
80
101
if ( t . isImportDeclaration ( node ) ) {
102
+ // Handle import statements
81
103
imports . push ( node ) ;
82
104
node . specifiers . forEach ( ( specifier ) => {
83
105
importedIdentifiers . add ( specifier . local . name ) ;
84
106
} ) ;
107
+ } else if ( t . isVariableDeclaration ( node ) ) {
108
+ node . declarations . forEach ( ( declaration ) => {
109
+ if (
110
+ t . isCallExpression ( declaration . init ) &&
111
+ t . isIdentifier ( declaration . init . callee , { name : "require" } ) &&
112
+ declaration . init . arguments . length === 1 &&
113
+ t . isStringLiteral ( declaration . init . arguments [ 0 ] )
114
+ ) {
115
+ let importDeclaration =
116
+ convertRequireIntoImportStatement ( declaration ) ;
117
+ imports . push ( importDeclaration ) ;
118
+ importedIdentifiers . add ( declaration . id . name ) ; // Track the imported identifier
119
+ }
120
+ } ) ;
85
121
}
86
122
} ) ;
87
123
0 commit comments