Skip to content

Instantly share code, notes, and snippets.

@rajeshkumaravel
Forked from tinovyatkin/getAllImports.ts
Created February 16, 2023 06:40
Show Gist options
  • Save rajeshkumaravel/1be4bed835e9ef27148bd3c2db36e311 to your computer and use it in GitHub Desktop.
Save rajeshkumaravel/1be4bed835e9ef27148bd3c2db36e311 to your computer and use it in GitHub Desktop.
Getting all imported modules names from a JS file using TypeScript parser
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