Skip to content

Instantly share code, notes, and snippets.

@tinovyatkin
Last active December 3, 2023 11:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tinovyatkin/727ddbf7e7e10831a1eca9e4ff2fc32e to your computer and use it in GitHub Desktop.
Save tinovyatkin/727ddbf7e7e10831a1eca9e4ff2fc32e 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