Search code examples
sveltekit

Sveltekit: how to remove HTML comments from app.html in production build?


I would like to strip HTML comments of app.html in my Sveltekit prduction build (and keep them in app.html during development), how to do it ?

The only thing I thought of would be an end-build step with some regex like described in Remove HTML and Javascript comments automatically


Solution

  • You can use env variables + hooks.server.js file

    1: In your .env.development and/or env.preview

    PUBLIC_ENV=development
    

    2: In your hooks.server.js, override the html ( similar php/.net outputbuffer filter hooks )

    import { PUBLIC_ENV } from '$env/static/public';
    
    const outputbuffer = ( html ) =>
    {
    
        // DO YOU WORK HERE TO ALTER THE HTML STRING
    
        return html;
    }
    
    export const handle = async ({ event, resolve }) => 
    {
       let response = await resolve( event, 
       {
         transformPageChunk: async ({ html }) => 
         {
           if ( PUBLIC_ENV !== 'production' ) return outputbuffer( html );
         }
       });
    
       return response;
    }