Created
June 5, 2024 18:16
-
-
Save jameswomack/872dcf472c6bbd1ff89fde571185a115 to your computer and use it in GitHub Desktop.
Parse imports from TypeScript files
This file contains hidden or 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
// Use like `node ts-module-lexer.js packages/extensions/foo/src/extension.ts` | |
const fs = require('fs'); | |
const path = require('path'); | |
const ts = require('typescript'); | |
const [_processName, _scriptName, ...args] = process.argv; | |
const fileName = path.basename(args[0]); | |
const sourceText = fs.readFileSync(args[0], 'utf8'); | |
// eslint-disable-next-line no-console | |
console.info(`Parsing imports for ${fileName} at path ${args[0]}`); | |
const node = ts.createSourceFile(fileName, sourceText, ts.ScriptTarget.Latest); | |
const importStatements = node.statements.filter(ts.isImportDeclaration); | |
const massagedImportStatements = importStatements.map(importStatement => { | |
const { moduleSpecifier } = importStatement; | |
const { importClause } = importStatement; | |
const retVal = { | |
importedModuleString: moduleSpecifier.text | |
}; | |
if (importClause) { | |
if (importClause.namedBindings) { | |
if (ts.isNamedImports(importClause.namedBindings)) { | |
retVal.whatWasImported = importClause.namedBindings.elements.map(element => element.name.text); | |
} else if (ts.isNamespaceImport(importClause.namedBindings)) { | |
retVal.namespace = importClause.namedBindings.name.text; | |
} | |
} | |
} | |
return retVal; | |
}); | |
// eslint-disable-next-line no-console | |
console.dir(massagedImportStatements, { depth: 3 }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example output: