-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvite.config.ts
More file actions
87 lines (71 loc) · 2.41 KB
/
vite.config.ts
File metadata and controls
87 lines (71 loc) · 2.41 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { defineConfig, type Plugin } from "vite";
import react from "@vitejs/plugin-react";
// import { defineConfig } from "vite";
import fs from "node:fs";
import path from "node:path";
function prettyStaticPages(): Plugin {
const routes = new Set(["/about", "/privacy", "/terms", "/contact"]);
const rewrite = (req: any) => {
const raw = String(req.url || "");
const [path, query] = raw.split("?");
const clean = path.endsWith("/") ? path.slice(0, -1) : path;
if (routes.has(clean)) {
req.url = `${clean}/index.html${query ? `?${query}` : ""}`;
}
};
return {
name: "pretty-static-pages",
configureServer(server) {
server.middlewares.use((req, _res, next) => {
rewrite(req);
next();
});
},
configurePreviewServer(server) {
server.middlewares.use((req, _res, next) => {
rewrite(req);
next();
});
},
};
}
function publicFolderIndexHtmlRewrite() {
const rewrite = (req: any, publicDir: string) => {
const raw = req.url || "/";
const u = new URL(raw, "http://local.test");
const pathname = decodeURIComponent(u.pathname);
// ignore root and obvious files
if (pathname === "/") return null;
const hasExt = path.posix.extname(pathname) !== "";
const candidateDir = pathname.endsWith("/") ? pathname : (!hasExt ? pathname + "/" : null);
if (!candidateDir) return null;
const rel = candidateDir.replace(/^\/+/, ""); // strip leading /
const indexFsPath = path.join(publicDir, rel, "index.html");
if (!fs.existsSync(indexFsPath)) return null;
// rewrite /uk/ -> /uk/index.html (keep querystring)
return candidateDir + "index.html" + u.search;
};
const attach = (server: any) => {
server.middlewares.use((req: any, _res: any, next: any) => {
const publicDir = server.config.publicDir;
const nextUrl = rewrite(req, publicDir);
if (nextUrl) req.url = nextUrl;
next();
});
};
return {
name: "public-folder-index-html-rewrite",
apply: "serve" as const,
configureServer(server: any) {
attach(server);
},
// also makes `vite preview` behave the same
configurePreviewServer(server: any) {
attach(server);
},
};
}
export default defineConfig({
// appType: "mpa", // ✅ makes /uk/ resolve to public/uk/index.html instead of SPA fallback
plugins: [react(), prettyStaticPages(), publicFolderIndexHtmlRewrite()],
});