DEV Community

John Winston
John Winston

Posted on

Minifying HTML response in SvelteKit

By default, SvelteKit only minifies CSS and JavaScript, leaving HTML untouched.

To enable HTML minification regardless of the adapter in use, you can process the HTML response in hooks.server.js or hooks.server.ts using an HTML minification library. Below is an example that demonstrates how to achieve this with the html-minifier library.

// src/hooks.server.ts
import { minify } from 'html-minifier';
import { type Handle } from '@sveltejs/kit';

const minifyOpts = {
  collapseBooleanAttributes: true,
  collapseWhitespace: true,
  conservativeCollapse: true,
  decodeEntities: true,
  html5: true,
  ignoreCustomComments: [/^#/],
  minifyCSS: true,
  minifyJS: false,
  removeAttributeQuotes: true,
  removeComments: false,
  removeOptionalTags: true,
  removeRedundantAttributes: true,
  removeScriptTypeAttributes: true,
  removeStyleLinkTypeAttributes: true,
  sortAttributes: true,
  sortClassName: true,
};

export const handle: Handle = async ({ event, resolve }) => {
  return resolve(event, {
    transformPageChunk: ({ html, done }) => {
      return minify(html, minifyOpts);
    },
  });
};
Enter fullscreen mode Exit fullscreen mode

If you like these performance tweaks, be sure to visit my guide on optimizing the performance of your SvelteKit project.

Image of AssemblyAI

Automatic Speech Recognition with AssemblyAI

Experience near-human accuracy, low-latency performance, and advanced Speech AI capabilities with AssemblyAI's Speech-to-Text API. Sign up today and get $50 in API credit. No credit card required.

Try the API

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay