forked from gothinkster/realworld-starter-kit
-
Notifications
You must be signed in to change notification settings - Fork 3
/
bundle-for-deno.ts
92 lines (77 loc) · 2.5 KB
/
bundle-for-deno.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
import path from "path";
import fs from "fs";
import deno from "@hattip/bundler-deno";
import { polyfillNodeForDeno } from "esbuild-plugin-polyfill-node";
export async function bundleForDeno(root: string) {
const input = path.resolve(root, "dist/server/entry-deno.js");
await fs.promises.writeFile(input, DENO_ENTRY);
await generateStaticAssetManifest(root);
deno(
{
input,
output: path.resolve(root, "dist/deno/mod.js"),
staticDir: "dist/client",
},
(options) => {
options.define = options.define || {};
options.define["process.env.NODE_ENV"] = '"production"';
options.define["process.env.RAKKAS_PRERENDER"] = "undefined";
options.plugins = options.plugins || [];
options.plugins.push(polyfillNodeForDeno());
options.logLevel = "error";
},
).catch(() => {
process.exit(1);
});
}
async function generateStaticAssetManifest(root: string) {
const files = walk(path.resolve(root, "dist/client"));
await fs.promises.writeFile(
path.resolve(root, "dist/server/static-manifest.js"),
`export default new Set(${JSON.stringify([...files])})`,
);
}
function walk(
dir: string,
root = dir,
entries = new Set<string>(),
): Set<string> {
const files = fs.readdirSync(dir);
for (const file of files) {
const filepath = path.join(dir, file);
const stat = fs.statSync(filepath);
if (stat.isDirectory()) {
walk(filepath, root, entries);
} else {
entries.add("/" + path.relative(root, filepath).replace(/\\/g, "/"));
}
}
return entries;
}
const STD_VERSION = "0.160.0";
const DENO_ENTRY = `
import * as path from "https://deno.land/std@${STD_VERSION}/path/mod.ts";
import { serve } from "https://deno.land/std@${STD_VERSION}/http/server.ts";
import { serveDir } from "https://deno.land/std@${STD_VERSION}/http/file_server.ts";
import { createRequestHandler } from "@hattip/adapter-deno";
import handler from "./hattip.js";
import staticFiles from "./static-manifest.js";
const staticDir = path.join(path.dirname(path.fromFileUrl(import.meta.url)), "public");
const denoHandler = createRequestHandler(handler);
serve(
async (request, connInfo) => {
const url = new URL(request.url);
const path = url.pathname;
if (staticFiles.has(path)) {
return serveDir(request, { fsRoot: staticDir });
} else if (staticFiles.has(path + "/index.html")) {
url.pathname = path + "/index.html";
return serveDir(new Request(url, request), { fsRoot: staticDir });
}
return denoHandler(request, connInfo);
},
{
port: Number(process.env.PORT) || 3000,
},
);
`;