-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
68 lines (60 loc) · 1.88 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
56
57
58
59
60
61
62
63
64
65
66
67
68
const path = require("path")
const fs = require("fs")
const esm = require('esm')(module);
module.exports = function TaorAppRouter(ctx, options) {
const sourcePath = ctx.paths.sourcePath;
const config = options?.config ?? "app.config.ts";
const root = options?.root ?? "app";
const page = options?.page ?? "page";
function getRoutes() {
const basePath = path.join(sourcePath, root);
const routes = new Set();
function readDirRecursiveSync(currentDir) {
const files = fs.readdirSync(currentDir, { withFileTypes: true });
let hasPageFile = false;
for (const file of files) {
const fullPath = path.join(currentDir, file.name);
if (file.isDirectory()) {
readDirRecursiveSync(fullPath);
} else if (
file.isFile() &&
new RegExp(`^${page}\.(tsx|jsx|ts|js)$`).test(file.name)
) {
hasPageFile = true;
}
}
if (hasPageFile) {
routes.add(
path
.join(root, path.relative(basePath, currentDir), page)
.replace(/\\/g, "/")
);
}
}
readDirRecursiveSync(basePath);
return [...routes];
}
function createRouter() {
const configPath = path.join(sourcePath, config);
const exportValue = esm(configPath);
const configValue = exportValue.default ?? exportValue;
const newPages = getRoutes();
if (JSON.stringify(configValue.pages) !== JSON.stringify(newPages)) {
configValue.pages = newPages;
fs.writeFileSync(
configPath,
`const config = ${JSON.stringify(configValue, null, 2)}` +
`\nexport default config\n`
);
}
}
class TaroAutoRouter {
apply(compiler) {
compiler.hooks.watchRun.tap("create router", createRouter);
}
}
createRouter();
ctx.modifyWebpackChain(({ chain }) => {
chain.plugin("taro-auto-router").use(TaroAutoRouter);
});
}