Astro: How to Set Up More Powerful HTML Minification (in 31 Seconds)
Published on MarĀ 17, 2026, filed under development, html, optimization. (Share this post, e.g. on Mastodon or onĀ Bluesky.)
Youāre running an Astro site and want to squeeze more out of your HTML (and inline CSS, JS, and SVG)?
HTML Minifier Next (HMN) gets you more effective results than the setup Astro ships with (at least when testing against AstroĀ 6.0.4).
It takes just two steps to set up HMN, which you can customize further afterwards:
1. Install
Install HMN in your project (as a dev dependency):
npm i -D html-minifier-next2. Configure
Add the following to your Astro configuration (astro.config.js or similar):
// Close to other imports:
import { readFileSync, writeFileSync, readdirSync } from 'fs';
import { join } from 'path';
import { fileURLToPath } from 'url';
import { minify } from 'html-minifier-next';
// Before `defineConfig`:
function htmlMinifier() {
return {
name: 'html-minifier-next',
hooks: {
'astro:build:done': async ({ dir }) => {
const distDir = fileURLToPath(dir);
const files = readdirSync(distDir, { recursive: true, encoding: 'utf-8' })
.filter(f => f.endsWith('.html'))
.map(f => join(distDir, f));
for (const file of files) {
const minified = await minify(readFileSync(file, 'utf-8'), { preset: 'comprehensive' });
writeFileSync(file, minified);
}
}
}
};
}
// In `defineConfig` block:
integrations: [htmlMinifier()],And thatās it.
The configuration uses HMNās ācomprehensiveā preset for a pretty competitive result, but you can switch to the āconservativeā preset or fully customize minification.
Then, does this take 31 seconds? Contrary to me timing this with Eleventy, I donāt knowāthis time, Iām just making up the numberĀ š
Jonas Geiler provides a wrapper with astro-html-minifier-next. I didnāt try itāI wanted to develop a better feeling for Astro and for setting up HMN in an Astro projectā, but maybe you like that solution, too!
About Me
Iām Jens (long: Jens Oliver Meiert), and Iām an engineering lead, guerrilla philosopher, and indie publisher. Iāve worked as a technical lead and engineering manager for companies you use every day (like Google) and companies youāve never heard of, Iām an occasional contributor to web standards (like HTML, CSS, WCAG), and I write and review books for OāReilly and Frontend Dogma.
I love trying things, not only in web development and engineering management, but also with respect to politics and philosophy. Here on meiert.com I talk about some of my experiences and perspectives. (Please share feedback: Interpret charitably, but do be critical.)
