Run npx tsx generate-exports.ts
Created
June 13, 2024 16:57
-
-
Save iursevla/bdb8f1a74fa7f665efde685021ffd73b to your computer and use it in GitHub Desktop.
Generate index.ts for all typescript files within your project
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
import fs from 'fs'; | |
import * as path from 'node:path'; | |
// Directory containing your components | |
const srcDir = path.resolve(__dirname, 'src'); | |
// Output file | |
const indexFile = path.resolve(__dirname, 'src/index.ts'); | |
// Helper function to recursively get all TypeScript files | |
const getAllFiles = (dir: string, files: string[] = []) => { | |
const items = fs.readdirSync(dir); | |
items.forEach(item => { | |
const fullPath = path.join(dir, item); | |
if (fs.statSync(fullPath).isDirectory()) { | |
getAllFiles(fullPath, files); | |
} else if (item.endsWith('.ts') && item !== 'index.ts') { | |
files.push(fullPath); | |
} | |
}); | |
return files; | |
}; | |
// Generate export statements | |
const files = getAllFiles(srcDir); | |
const exportStatements = files.map(file => { | |
const relativePath = path.relative(__dirname, file).replace(/\\/g, '/').replace(/\.ts$/, '').replace('src', ''); | |
return `export * from '.${relativePath}';`; | |
}).join('\n'); | |
// Write export statements to index.ts | |
fs.writeFile(indexFile, exportStatements, err => { | |
if (err) { | |
console.error("Could not write index file.", err); | |
process.exit(1); | |
} | |
console.log('index.ts has been generated successfully.'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment