-
-
Save rajeshkumaravel/1be4bed835e9ef27148bd3c2db36e311 to your computer and use it in GitHub Desktop.
Getting all imported modules names from a JS file using TypeScript parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { readFileSync } from 'fs'; | |
import { builtinModules } from 'module'; | |
import ts from 'typescript'; | |
const tsHost = ts.createCompilerHost( | |
{ | |
allowJs: true, | |
noEmit: true, | |
isolatedModules: true, | |
resolveJsonModule: false, | |
moduleResolution: ts.ModuleResolutionKind.Classic, // we don't want node_modules | |
incremental: true, | |
noLib: true, | |
noResolve: true, | |
}, | |
true, | |
); | |
function getImports(fileName: string): readonly string[] { | |
const sourceFile = tsHost.getSourceFile( | |
fileName, | |
ts.ScriptTarget.Latest, | |
(msg) => { | |
throw new Error(`Failed to parse ${fileName}: ${msg}`); | |
}, | |
); | |
if (!sourceFile) throw ReferenceError(`Failed to find file ${fileName}`); | |
const importing: string[] = []; | |
delintNode(sourceFile); | |
return { | |
importing, | |
}; | |
function delintNode(node: ts.Node) { | |
if (ts.isImportDeclaration(node)) { | |
const moduleName = node.moduleSpecifier.getText().replace(/['"]/g, ''); | |
if ( | |
!moduleName.startsWith('node:') && | |
!builtinModules.includes(moduleName) | |
) | |
importing.push(moduleName); | |
} else ts.forEachChild(node, delintNode); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment