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.

Top comments (0)