-
Notifications
You must be signed in to change notification settings - Fork 0
/
client-builder.js
79 lines (68 loc) · 2.08 KB
/
client-builder.js
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
import * as esbuild from "esbuild";
import { transformFileSync } from "@babel/core";
import { createWriteStream, unlinkSync, watch, writeFileSync } from "fs";
import browserify from "browserify";
const b = browserify();
const entryFile = "./client.ts";
const esbuildTempFile = "./static/client.esbuild.js";
watch(entryFile, async (eventType, filename) => {
b.add("./metafills.js");
// const writableStream = createWriteStream("./out");
const readStream = b.bundle();
console.log("Rebuilding the client...");
if (!(filename && eventType === "change")) {
return;
}
const browserifiedMetaFillsPromise = new Promise((resolve, reject) => {
const chunks = [];
readStream.on("data", function (chunk) {
chunks.push(chunk);
});
// Send the buffer or you can put it into a var
readStream.on("end", function () {
resolve(Buffer.concat(chunks));
readStream.removeAllListeners();
});
});
writeFileSync(
"./static/browserify.middle.js",
await browserifiedMetaFillsPromise,
);
// Esbuild does:
// - bundling!!
// - stripping TS
// - const -> var
// - async -> promises (I think)
const esbuildResult = await esbuild.build(
{
entryPoints: ["./client.ts"],
bundle: true,
// https://esbuild.github.io/content-types/#es5
// https://esbuild.github.io/content-types/#javascript
platform: "browser",
format: "iife",
target: "es2015",
// target: "ie11",
outfile: esbuildTempFile,
},
);
// Babel does:
// - convert template strings to .concat()
// - convert arrow functions to function()
const { code: babelCode } = transformFileSync(esbuildTempFile);
// Extra stuff!
const transformedCode =
((await browserifiedMetaFillsPromise) + "\n" + babelCode)
// Prevent SyntaxError: Parse Error
// .return subscript is not allowed
.replace(/\.return/g, '["return"]')
// .replace(/,\)/g, ")")
.replace(/,(?:\n\s+)?\)/gm, ")");
writeFileSync(
"./static/client.js",
transformedCode,
"utf-8",
);
b.reset();
// unlinkSync(esbuildTempFile);
});