-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.js
executable file
·98 lines (88 loc) · 2.72 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
91
92
93
94
95
96
97
98
import * as esbuild from "esbuild"
import { writeFile, realpathSync } from "node:fs"
import { resolve as resolvePath, relative as relativePath } from "node:path"
const cwd = process.cwd()
const [, , wwwRoot, ...entryPoints] = process.argv
if (!wwwRoot.length || wwwRoot.endsWith("/") || !entryPoints.length) {
throw new Error("Invalid wwwRoot or entryPoints")
}
const outbase = "assets"
const outdir = relativePath(cwd, resolvePath(realpathSync(wwwRoot), outbase))
const isProduction = process.env.NODE_ENV === "production"
const publicPath = "/static/assets/"
const context = await esbuild.context({
define: {
DEV: (!isProduction).toString(),
},
entryPoints,
outdir,
outbase,
entryNames: isProduction ? "[dir]/[name]-[hash]" : undefined,
format: "esm",
publicPath,
bundle: true,
minify: true,
sourcemap: isProduction ? false : "linked",
splitting: true,
treeShaking: true,
metafile: true,
platform: "browser",
target: ["safari13", "firefox68"],
loader: {
".png": "file",
},
plugins: [
{
name: "outputMap",
setup: (build) =>
build.onEnd((result) => {
const ob = Object.keys(result?.metafile?.outputs || {}).reduce((acc, file) => {
const { entryPoint } = result.metafile.outputs[file]
if (entryPoint) {
const entryPath = entryPoint.substring(entryPoint.indexOf(outbase) - 1)
const outPath = `${publicPath}${relativePath(outdir, file)}`
acc[entryPath] = outPath
}
return acc
}, {})
result.outputMap = ob
}),
},
{
name: "writeAssetsEx",
setup: (build) =>
build.onEnd(
(result) =>
new Promise((resolve, reject) => {
const metaContents = `# Generated by build.js, do not edit.
defmodule Nextcast.Assets do
def output_map do
%{
${Object.entries(result.outputMap).reduce((acc, [entryPath, outPath], ix, arr) => {
const delimiter = arr.length - 1 === ix ? "" : ",\n"
return `${acc}"${entryPath}" => "${outPath}"${delimiter}`
}, "")}
}
end
end
`
const manifestPath = resolvePath("lib", "_assets.ex")
writeFile(manifestPath, metaContents, (err) => {
if (err) return reject(err)
console.info(`[build.js] Wrote ${manifestPath}`)
resolve()
})
}),
),
},
],
})
if (!isProduction) {
await context.watch()
const { host, port } = await context.serve({ port: (+process.env.TCP_PORT || 8000) + 1 });
console.info(`[build.js] Watching and serving on ${host}:${port}...`)
} else {
await context.rebuild()
console.info("[build.js] Done!")
await context.dispose()
}