-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathframework.ts
94 lines (81 loc) · 2.49 KB
/
framework.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
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
88
89
90
91
92
93
94
import { getRequestListener } from "@hono/node-server";
import fs from "node:fs/promises";
import path from "node:path";
import {
createServerModuleRunner,
normalizePath,
Plugin,
ViteDevServer,
} from "vite";
export const environmentNames = {
client: "client",
ssr: "ssr",
};
const serverEntry = "./src/ssr/server.ts";
export function frameworkPlugin(): Plugin {
const clientEntry = "./src/client/index.html";
const ssrEntry = "./src/ssr/main.ts";
let viteServer: ViteDevServer | undefined;
return {
name: "framework-plugin",
config() {
return {
appType: "custom",
environments: {
[environmentNames.client]: {
build: {
rollupOptions: {
input: normalizePath(path.resolve(clientEntry)),
},
outDir: "dist/client",
emptyOutDir: false,
},
},
[environmentNames.ssr]: {
build: {
rollupOptions: {
input: normalizePath(path.resolve(serverEntry)),
},
outDir: "dist/ssr",
emptyOutDir: false,
copyPublicDir: false,
},
},
},
builder: {
async buildApp(builder) {
await fs.rm(path.resolve(builder.config.root, "dist"), {
recursive: true,
force: true,
});
await builder.build(builder.environments[environmentNames.client]);
await builder.build(builder.environments[environmentNames.ssr]);
await fs.rename(
path.resolve(builder.config.root, "dist/client", clientEntry),
path.resolve(builder.config.root, "dist/ssr/index.html")
);
},
},
};
},
async configureServer(server) {
const ssrRunner = createServerModuleRunner(
server.environments[environmentNames.ssr]
);
const module = await ssrRunner.import(ssrEntry);
const handler = getRequestListener(module.app.fetch);
return () => server.middlewares.use(handler);
},
async load(id) {
console.log("load id", id);
if (id.endsWith("?transformIndexHtml")) {
const cleanId = id.replace("?transformIndexHtml", "");
let content = await fs.readFile(cleanId, "utf-8");
if (viteServer) {
content = await viteServer.transformIndexHtml("/", content);
}
return `export default ${JSON.stringify(content)}`;
}
},
};
}