reosablo-samplevanssr.web.val.run
Readme

simple SSR + hydration example with VanJS

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
/** cached client HTML */
let clientHtml: string | undefined;
/** load client HTML */
async function loadClientHtml() {
// import VanJS framework and App component
const [{ default: van }, { default: App }] = await Promise.all([
import("npm:mini-van-plate@0.5.6/van-plate"),
import("https://esm.town/v/reosablo/sampleVanIsland"),
]);
const { body, h1, head, script, title } = van.tags;
return van.html(
head(
title("UUID v4 Generator"),
script({ type: "module", src: "/main.js" }),
),
body(
h1("UUID v4 Generator"),
// render App component
App({ van }),
),
);
}
/** cached client script for App component hydration */
let clientScript: string | undefined;
/** load client script for App component hydration */
async function loadClientScript() {
// import esbuild and plugins
const [{ build }, { denoPlugins }] = await Promise.all([
import("https://deno.land/x/esbuild@v0.20.2/wasm.js"),
import("https://deno.land/x/esbuild_deno_loader@0.9.0/mod.ts"),
]);
const result = await build({
plugins: [...denoPlugins({ loader: "portable" })],
// same path as in line 9
entryPoints: ["https://esm.town/v/reosablo/sampleVanIsland"],
bundle: true,
format: "esm",
minify: true,
write: false,
// required to avoid read permission of CWD by esbuild_deno_loader
absWorkingDir: "/",
});
return result.outputFiles[0].text;
}
export default async function fetch(req: Request) {
try {
const { pathname } = new URL(req.url);
switch (`${req.method} ${pathname}`) {
case "GET /": {
clientHtml ??= await loadClientHtml();
return new Response(clientHtml, {
headers: { "Content-Type": "text/html" },
});
}
case "GET /main.js": {
clientScript ??= await loadClientScript();
return new Response(clientScript, {
headers: { "Content-Type": "text/javascript" },
});
}
default: {
return new Response("Not found", { status: 404 });
}
}
} catch (error) {
return new Response(error.stack, { status: 500 });
}
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
May 4, 2024