Logo

dev-resources.site

for different kinds of informations.

Minifying HTML response in SvelteKit

Published at
1/16/2025
Categories
svelte
sveltekit
Author
John Winston
Categories
2 categories in total
svelte
open
sveltekit
open
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);
    },
  });
};

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

Featured ones: