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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more