Skip to content

Instantly share code, notes, and snippets.

@iursevla
Created June 13, 2024 16:57
Show Gist options
  • Save iursevla/bdb8f1a74fa7f665efde685021ffd73b to your computer and use it in GitHub Desktop.
Save iursevla/bdb8f1a74fa7f665efde685021ffd73b to your computer and use it in GitHub Desktop.
Generate index.ts for all typescript files within your project
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.');
});

Run npx tsx generate-exports.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment