-
Notifications
You must be signed in to change notification settings - Fork 0
/
vite.config.ts
122 lines (109 loc) · 2.89 KB
/
vite.config.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
import { defineConfig } from "vite";
import { relative } from "node:path";
import ssg from "@hono/vite-ssg";
import { Hono } from "hono";
import {} from "hono/router";
import { toSSG } from "hono/ssg";
import type { Plugin, ResolvedConfig } from "vite";
import { createServer } from "vite";
import { unstable_dev } from "wrangler";
type SSGOptions = {
entry?: string;
};
export const defaultOptions: Required<SSGOptions> = {
entry: "./src/index.tsx",
};
export const ssgBuild = (options?: SSGOptions): Plugin => {
const virtualId = "virtual:ssg-void-entry";
const resolvedVirtualId = "\0" + virtualId;
const entry = options?.entry ?? defaultOptions.entry;
let config: ResolvedConfig;
return {
name: "@hono/vite-ssg",
apply: "build",
async config() {
return {
build: {
rollupOptions: {
input: [virtualId],
},
},
};
},
configResolved(resolved) {
config = resolved;
},
resolveId(id) {
if (id === virtualId) {
return resolvedVirtualId;
}
},
load(id) {
if (id === resolvedVirtualId) {
return 'console.log("suppress empty chunk message")';
}
},
async generateBundle(_outputOptions, bundle) {
for (const chunk of Object.values(bundle)) {
if (
chunk.type === "chunk" &&
chunk.moduleIds.includes(resolvedVirtualId)
) {
delete bundle[chunk.fileName];
}
}
// Create a server to load the module
const server = await createServer({
plugins: [],
build: { ssr: true },
});
const module = await server.ssrLoadModule(entry);
server.close();
const app = module["default"] as Hono;
if (!app) {
throw new Error(
`Failed to find a named export "default" from ${entry}`,
);
}
const worker = await unstable_dev(entry, {
local: false,
config: "./wrangler.toml",
experimental: {
disableExperimentalWarning: true,
},
});
const _app = new Hono();
for (const route of app.routes) {
_app.on(route.method, [route.path], async (c) => {
const res = await worker.fetch(c.req.url);
return res as unknown as Response;
});
}
const outDir = config.build.outDir;
const result = await toSSG(
_app,
{
writeFile: async (path, data) => {
// delegate to Vite to emit the file
this.emitFile({
type: "asset",
fileName: relative(outDir, path),
source: data,
});
},
async mkdir() {
return;
},
},
{ dir: outDir },
);
await worker.stop();
if (!result.success) {
throw result.error;
}
},
};
};
export default defineConfig({
plugins: [ssgBuild()],
});