-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcreate-index.ts
54 lines (42 loc) · 1.31 KB
/
create-index.ts
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
import { promises } from 'fs';
import { filter, traverse } from 'fs-match';
import { join } from 'path';
import { parse } from 'yaml';
const title = 'MDX index creator',
[folder] = process.argv.slice(2);
const MDXPattern = /\.(mdx?|markdown)$/,
sourceCode: string[] = [],
targetPath = join(folder, 'index.ts');
console.time(title);
(async () => {
for await (const filePath of filter(traverse(folder), MDXPattern)) {
const content = await promises.readFile(filePath, {
encoding: 'utf-8'
});
const [_, frontMatter] =
content.match(/^---([\s\S]*?)[\r\n]+---/m) || [];
if (!frontMatter) continue;
const meta = JSON.stringify(parse(frontMatter), null, 4)
.slice(1, -1)
.trim();
const path = filePath.replaceAll('\\', '/').slice(folder.length);
sourceCode.push(`{
path: '${path.replace(MDXPattern, '')}',
${meta},
component: lazy(loadMDX(() => import('./${path}')))
}`);
}
await promises.writeFile(
targetPath,
`// This file is created by "${title}" script,
// please don't edit it manually!
import { lazy } from 'web-cell';
import { loadMDX } from '../utility';
export default [
${sourceCode}
];
`
);
console.log(`[save] ${targetPath}`);
console.timeEnd(title);
})();