-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.js
90 lines (73 loc) · 2.02 KB
/
build.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
80
81
82
83
84
85
86
87
88
89
90
import { Parcel } from "@parcel/core";
import { cp, readdir, readFile, rm, writeFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
const buildDirectory = "./dist";
const staticDirectory = "./static";
async function clear() {
console.log("Clearing build directory %s", buildDirectory);
await rm(buildDirectory, { recursive: true, force: true });
}
async function build() {
const bundler = new Parcel({
entries: [
"./frontend/index.html",
"./frontend/404.html",
"./frontend/en/index.html",
"./frontend/en/404.html",
],
mode: "production",
additionalReporters: [
{
packageName: "@parcel/reporter-cli",
resolveFrom: fileURLToPath(import.meta.url),
},
],
});
await bundler.run();
}
async function generateHeadersFile() {
const hashedAssetNamePattern = /\.[a-f0-9]{8}\.[a-z0-9]{2,5}(?:\.map)?$/;
const files = await readdir(buildDirectory, { recursive: true });
const hashedAssets = files.filter((file) =>
hashedAssetNamePattern.test(file),
);
console.log(
"Appending cache rules to _headers file for %d cached assets",
hashedAssets.length,
);
const template = await readFile(`${staticDirectory}/_headers`, {
encoding: "utf-8",
});
const headersContent =
template +
"\n" +
hashedAssets
.map(
(fileName) =>
`/${fileName}\n Cache-Control: max-age=31536000, immutable`,
)
.join("\n") +
"\n";
console.log("Writing _headers file to %s", buildDirectory);
await writeFile(`${buildDirectory}/_headers`, headersContent, {
encoding: "utf-8",
});
}
async function copyStaticFiles() {
console.log(
"Copying other static files from %s to %s",
staticDirectory,
buildDirectory,
);
await cp(staticDirectory, buildDirectory, {
recursive: true,
filter: (sourcePath) => !sourcePath.endsWith("_headers"),
});
}
async function init() {
await clear();
await build();
await generateHeadersFile();
await copyStaticFiles();
}
await init();