Skip to content

Commit d181406

Browse files
authored
chore: minify json files (@fehmer) (monkeytypegame#6404)
1 parent b1d75fb commit d181406

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

frontend/vite.config.prod.js

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { checker } from "vite-plugin-checker";
1010
import { writeFileSync } from "fs";
1111
// eslint-disable-next-line import/no-unresolved
1212
import UnpluginInjectPreload from "unplugin-inject-preload/vite";
13+
import { readdirSync, readFileSync, statSync } from "node:fs";
1314

1415
function pad(numbers, maxLength, fillString) {
1516
return numbers.map((number) =>
@@ -169,6 +170,69 @@ export default {
169170
],
170171
injectTo: "head-prepend",
171172
}),
173+
{
174+
name: "minify-json",
175+
apply: "build",
176+
generateBundle() {
177+
let totalOriginalSize = 0;
178+
let totalMinifiedSize = 0;
179+
180+
const minifyJsonFiles = (dir) => {
181+
readdirSync(dir).forEach((file) => {
182+
const sourcePath = path.join(dir, file);
183+
const stat = statSync(sourcePath);
184+
185+
if (stat.isDirectory()) {
186+
minifyJsonFiles(sourcePath);
187+
} else if (path.extname(file) === ".json") {
188+
const originalContent = readFileSync(sourcePath, "utf8");
189+
const originalSize = Buffer.byteLength(originalContent, "utf8");
190+
const minifiedContent = JSON.stringify(
191+
JSON.parse(originalContent)
192+
);
193+
const minifiedSize = Buffer.byteLength(minifiedContent, "utf8");
194+
195+
totalOriginalSize += originalSize;
196+
totalMinifiedSize += minifiedSize;
197+
198+
const savings =
199+
((originalSize - minifiedSize) / originalSize) * 100;
200+
201+
writeFileSync(sourcePath, minifiedContent);
202+
203+
console.log(
204+
`\x1b[0m \x1b[36m${sourcePath}\x1b[0m | ` +
205+
`\x1b[90mOriginal: ${originalSize} bytes\x1b[0m | ` +
206+
`\x1b[90mMinified: ${minifiedSize} bytes\x1b[0m | ` +
207+
`\x1b[32mSavings: ${savings.toFixed(2)}%\x1b[0m`
208+
);
209+
}
210+
});
211+
};
212+
213+
console.log("\n\x1b[1mMinifying JSON files...\x1b[0m\n");
214+
215+
minifyJsonFiles("./dist");
216+
217+
const totalSavings =
218+
((totalOriginalSize - totalMinifiedSize) / totalOriginalSize) * 100;
219+
220+
console.log(
221+
`\n\x1b[1mMinification Summary:\x1b[0m\n` +
222+
` \x1b[90mTotal original size: ${(
223+
totalOriginalSize /
224+
1024 /
225+
1024
226+
).toFixed(2)} mB\x1b[0m\n` +
227+
` \x1b[90mTotal minified size: ${(
228+
totalMinifiedSize /
229+
1024 /
230+
1024
231+
).toFixed(2)} mB\x1b[0m\n` +
232+
` \x1b[32mTotal savings: ${totalSavings.toFixed(2)}%\x1b[0m\n`
233+
);
234+
},
235+
},
172236
],
173237
build: {
174238
emptyOutDir: true,

0 commit comments

Comments
 (0)