-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.mjs
More file actions
206 lines (177 loc) · 6.25 KB
/
build.mjs
File metadata and controls
206 lines (177 loc) · 6.25 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import esbuild from "esbuild";
//import browserslist from "browserslist";
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { bundle as lightningBundle, browserslistToTargets } from "lightningcss";
import browserslist from "browserslist";
//import browserslistToEsbuild from "./browserslistToEsbuild.mjs";
const OUTDIR = "static/dist";
async function generatePagesJson() {
const outDir = path.join(OUTDIR, "pages");
ensureDir(outDir);
const tempScript = path.join(OUTDIR, "export-pages.cjs");
await esbuild.build({
entryPoints: ["static/js/ExportPath.js"],
bundle: true,
platform: "node",
format: "cjs",
target: ["node18"],
outfile: tempScript,
banner: {
js: "globalThis.window = globalThis.window || globalThis;",
},
});
const runResult = spawnSync(process.execPath, [tempScript], {
stdio: "inherit",
env: {
...process.env,
EXPORT_PATH_OUTDIR: outDir,
},
});
if (runResult.status !== 0) {
throw new Error(`ExportPath build step failed with code ${runResult.status}`);
}
fs.unlinkSync(tempScript);
}
function ensureDir(dir) {
fs.mkdirSync(dir, { recursive: true });
}
function cleanOld(patterns, dir = OUTDIR) {
if (!fs.existsSync(dir)) return;
const files = fs.readdirSync(dir);
for (const f of files) {
if (patterns.some((re) => re.test(f))) {
fs.unlinkSync(path.join(dir, f));
}
}
}
function shortHash(buf) {
return crypto.createHash("sha256").update(buf).digest("hex").slice(0, 10);
}
//esbuild static/js/app.js --bundle --minify --sourcemap --target=es2015 --format=iife --outfile=static/js/app.dist.tmp2015.js
async function buildJS() {
//const ESBuildTargets = browserslistToEsbuild();
const result = await esbuild.build({
entryPoints: ["static/js/app.js"],
bundle: true,
minify: true,
sourcemap: true,
target: ["es2015"],//, ...ESBuildTargets],
format: "iife",
outdir: OUTDIR+"/js",
entryNames: "app.[hash]",
metafile: true,
//metafile: "static/dist/meta.json",
write: true,
});
// Trova il file JS generato (app.<hash>.js) dentro result.metafile.outputs
const outputs = Object.keys(result.metafile.outputs);
const jsOut = outputs.find((p) => p.replaceAll("\\", "/").match(/static\/dist\/js\/app\..+\.js$/));
if (!jsOut) throw new Error("JS output app.<hash>.js non trovato");
// Converti in path relativo a /static
//const rel = jsOut.replaceAll("\\", "/").replace(/^static\//, "");
const rel = jsOut;
const hash = rel.match(/app\.(.+)\.js$/)[1];
await buildBabel_2015(hash);
await esbuild.build({
entryPoints: [`static/dist/js/app.${hash}.js`],
bundle: true,
minify: true,
sourcemap: true,
target: ["es5"],
//target: ["es2015"],//, ...ESBuildTargets],
format: "iife",
outdir: OUTDIR+"/js",
metafile: true,
//metafile: "static/dist/meta.json",
write: true,
allowOverwrite: true,
});
return { js: rel };
}
//babel static/js/app.dist.tmp2015.js --out-file static/js/app.dist.js --presets=@babel/preset-env --plugins=./myplugin__define_var.cjs --minified --source-maps
async function buildBabel_2015(hash) {
const { exec } = await import("child_process");
return new Promise((resolve, reject) => {
exec(`npx babel static/dist/js/app.${hash}.js --out-file static/dist/js/app.${hash}.js --plugins=./myplugin__define_var.cjs --minified --source-maps`, (error, stdout, stderr) => {
if (error) {
reject(error);
} else {
resolve();
}
});
});
}
//esbuild static/styles.css --bundle --minify --sourcemap --target=chrome58,firefox57,safari11 --outdir=static/dist --entry-names=style.[hash] --metafile=static/dist/meta_css.json
async function buildCSS() {
const LightningCSStargets = browserslistToTargets(browserslist());
//const targets = browserslistToTargets(browserslist("> 2%, not dead")); // :contentReference[oaicite:3]{index=3}
/*const targets = {
chrome: 58,
firefox: 57,
safari: 11,
edge: 79,
ios_saf: 11
};*/
// bundle CSS (risolve @import), minify, sourcemap
const res = await lightningBundle({
filename: path.resolve("static/css/styles.css"),
bundle: true,
minify: true,
sourceMap: true,
LightningCSStargets,
outdir: OUTDIR+"/css",
entryNames: "style.[hash]",
metafile: true,
});
// res.code è Uint8Array; res.map è Uint8Array (sourcemap)
const cssCode = Buffer.from(res.code);
const cssMap = Buffer.from(res.map);
const h = shortHash(cssCode);
const cssName = `style.${h}.css`;
const mapName = `${cssName}.map`;
fs.writeFileSync(path.join(OUTDIR+"/css", cssName), cssCode);
fs.writeFileSync(path.join(OUTDIR+"/css", mapName), cssMap);
return { css: `static/dist/css/${cssName}` };
}
async function main() {
ensureDir(OUTDIR);
ensureDir(OUTDIR+"/js");
ensureDir(OUTDIR+"/css");
ensureDir(OUTDIR+"/pages");
// pulisci vecchi app.* e style.* (solo dentro static/dist)
cleanOld([
/^app\..+\.js$/,
/^app\..+\.js\.map$/,
], OUTDIR+"/js");
cleanOld([
/^style\..+\.css$/,
/^style\..+\.css\.map$/,
], OUTDIR+"/css");
cleanOld([
/^manifest\.json$/
], OUTDIR);
cleanOld([
/^pages_1_elementari\.json$/,
/^pages_2_medie\.json$/,
/^pages_3_liceo\.json$/,
/^pages_4_natale\.json$/,
/^pages_5_alien\.json$/,
/^pages_manifest\.json$/,
], OUTDIR+"/pages");
console.log("Generating pages JSON...");
await generatePagesJson();
console.log("Building JS...");
const js = await buildJS();
console.log("Building CSS...");
const css = await buildCSS();
const manifest = { ...js, ...css };
fs.writeFileSync(path.join(OUTDIR, "manifest.json"), JSON.stringify(manifest, null, 2));
console.log("Build OK:", manifest);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});