Skip to content

Instantly share code, notes, and snippets.

@piksel
Last active May 25, 2023 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piksel/88a78d9b1f22b17ad2c69db89086c306 to your computer and use it in GitHub Desktop.
Save piksel/88a78d9b1f22b17ad2c69db89086c306 to your computer and use it in GitHub Desktop.
Script for re-exporting all .ts(x) files in a directory
import { readdir, readFile, writeFile, access, stat } from 'node:fs/promises';
import { resolve } from 'node:path';
const [, , path] = process.argv;
const HEADER = '// AUTO-GENERATED by export-all.mjs DO NOT CHANGE!';
if (!path) {
console.error('Missing argument PATH')
process.exit(1);
}
const indexFilePath = resolve(path, 'index.ts');
if ((await access(indexFilePath).then(_ => true, _ => false))) {
const indexContent = await readFile(indexFilePath, { encoding: 'utf-8' });
if (!indexContent.startsWith(HEADER)) {
console.error('Index already exists!');
process.exit(2);
}
console.info('Replacing existing index.ts');
}
let indexContent = HEADER + "\n\n";
let indexExports = 0;
try {
const pattern = /\.tsx?$/gm;
const files = await readdir(path);
for (const file of files) {
if (file === 'index.ts') continue;
if (!file.match(pattern) && !(await stat(resolve(path, file))).isDirectory()) {
console.log('Skipping %o', file);
continue;
}
const fileWithoutExt = file.replace(pattern, '');
indexContent += `export * from './${fileWithoutExt}';\n`;
indexExports++;
}
if (indexExports < 1) {
console.warn('No exports found in path %o, skipping!', path);
process.exit(0);
}
await writeFile(indexFilePath, indexContent);
// console.log('Output:\n' + indexContent);
console.info('Added %o exports to %o!', indexExports, indexFilePath);
} catch (err) {
console.error(err);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment