-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
55 lines (48 loc) · 1.8 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/* eslint-disable @typescript-eslint/no-var-requires */
// this script is run as a pre-commit hook
// it generates index.ts files in each low-level dir that exports all the files in that dir
// this makes the imports shorter and easier to read
const fs = require('fs');
const path = require('path');
const SRC_DIR = 'src';
const INDEX_FILE = 'index';
function main() {
console.log('Generating index.ts files...');
getDirs(path.join(__dirname, SRC_DIR), 0);
}
function getDirs(dirPath, depth) {
const dirs = fs.readdirSync(dirPath).filter((file) => fs.statSync(path.join(dirPath, file)).isDirectory());
const files = fs.readdirSync(dirPath).filter((file) => fs.statSync(path.join(dirPath, file)).isFile());
// recurse into subdirs
dirs.forEach((dir) => {
const nestedIndexFile = getDirs(path.join(dirPath, dir), depth + 1);
if (nestedIndexFile) {
files.push(nestedIndexFile);
}
});
// write index.ts for these files
const indexFile = writeIndexTs(dirPath, files, depth);
return indexFile;
}
function writeIndexTs(dir, files, depth) {
const indexFile = path.join(dir, 'index.ts');
let indexFileContent = '';
files.forEach((file) => {
const baseName = path.basename(file, '.ts');
const isSubDirIndexFile = baseName === INDEX_FILE && file.split('/').length === 2;
// ignore index files
if (baseName !== INDEX_FILE) {
indexFileContent += `export * from './${baseName}';\n`;
} else if (isSubDirIndexFile && depth > 1) {
const subDirWithIndexFile = file.split('/')[0];
indexFileContent += `export * from './${subDirWithIndexFile}';\n`;
}
});
// write only if content is not empty
if (indexFileContent) {
fs.writeFileSync(indexFile, indexFileContent);
const baseName = path.basename(dir);
return path.join(baseName, 'index.ts');
}
}
main();