Created
June 15, 2023 00:24
-
-
Save danyelhenrique/5571a1902a318ee1d7a814b0ad8cdd88 to your computer and use it in GitHub Desktop.
generate types from directorty . Get all interfaces / types from project and put on one file
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
| const fs = require('fs') | |
| const path = require('path') | |
| const ts = require('typescript') | |
| class DeclarationsExtractor { | |
| constructor(srcDir, outputFilePath) { | |
| this.srcDir = srcDir | |
| this.outputFilePath = outputFilePath | |
| } | |
| processFiles(dir) { | |
| const files = fs.readdirSync(dir) | |
| files.forEach(file => { | |
| const filePath = path.join(dir, file) | |
| const stats = fs.statSync(filePath) | |
| if (stats.isFile() && file.endsWith('.ts')) { | |
| const fileContents = fs.readFileSync(filePath, 'utf8') | |
| const sourceFile = ts.createSourceFile( | |
| filePath, | |
| fileContents, | |
| ts.ScriptTarget.Latest, | |
| true | |
| ) | |
| const declarations = [] | |
| const visit = node => { | |
| if ( | |
| (ts.isInterfaceDeclaration(node) || | |
| ts.isTypeAliasDeclaration(node)) && | |
| node.name | |
| ) { | |
| const declaration = fileContents.substring(node.pos, node.end) | |
| declarations.push(declaration) | |
| } | |
| ts.forEachChild(node, visit) | |
| } | |
| visit(sourceFile) | |
| declarations.forEach(declaration => { | |
| fs.appendFileSync(this.outputFilePath, `${declaration}\n\n`) | |
| }) | |
| } else if (stats.isDirectory()) { | |
| this.processFiles(filePath) | |
| } | |
| }) | |
| } | |
| extractDeclarations() { | |
| this.processFiles(this.srcDir) | |
| console.log(`Arquivo ${this.outputFilePath} gerado com sucesso!`) | |
| } | |
| } | |
| const srcDir = './src' // Diretório com os arquivos TypeScript | |
| const outputFilePath = './declarations.d.ts' // Caminho do arquivo de saída | |
| const extractor = new DeclarationsExtractor(srcDir, outputFilePath) | |
| extractor.extractDeclarations() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment