Skip to content

Commit

Permalink
fix(tools): #21 Remove origional images from the bundel after deploy
Browse files Browse the repository at this point in the history
Our bundle was over 1.3gb due to all the high rez images being included in the build. They were not being used however. Due to some use cases Astro includes them by default, however Github's max deploy for pages is 1GB (with some flexibility). This promises to drasitcally reduce our bundle.
  • Loading branch information
bnjmnrsh committed Sep 16, 2024
1 parent ca5f945 commit 038eec9
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
4 changes: 3 additions & 1 deletion astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ import relativeLinks from 'astro-relative-links';
import purgecss from "astro-purgecss";
import purgeOpts from './purgecss.config.mjs'
import { getCurrentNonce } from "./src/js/getCurrentNonce";
import removeOriginalImages from "./src/intergrations/removeOriginalImages";
// import prebuild from "./src/intergrations/prebuild"; //prebuild()

export default defineConfig({
build: {
inlineStylesheets: 'auto'
},
// site: 'https://example.com', // We are not setting this as we want to deploy to domain mirrors, e.g. yourname.github.io and yourname.com.
integrations: [icon(), relativeLinks(), purgecss(purgeOpts)],
integrations: [icon(), relativeLinks(), purgecss(purgeOpts), removeOriginalImages],
output: 'static',
experimental: {
env: {
Expand Down
28 changes: 28 additions & 0 deletions src/intergrations/removeOriginalImages.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import fs from "node:fs/promises";
import path from "node:path";
import type { AstroIntegration } from "astro";

// In Astro 4, unused images are removed from the build, but some original images may still remain in the _astro folder.
const removeOriginalImages: AstroIntegration = {
name: 'remove-original-images',
hooks: {
'astro:build:done': async ({ dir }) => {
const astroDir = path.join(dir.pathname, `_astro/`);
const files = await fs.readdir(astroDir);
for (const file of files) {
const { name, ext } = path.parse(file);
const { ext: hashStr } = path.parse(name);
if (!ext) continue;
if (!hashStr) continue;
if (![`.jpg`, `.jpeg`, `.png`, `.webp`].includes(ext)) continue;
if (hashStr.includes(`_`)) continue;

console.log(`Removing original image: ${file}`);
await fs.unlink(path.join(astroDir, file));
}
}
}
}

export default removeOriginalImages;

0 comments on commit 038eec9

Please sign in to comment.