Using an HTML minifier for .svelte
files?
#2947
Replies: 3 comments 2 replies
-
Hey try this example below: // src/hooks.server.js
import { minify } from 'html-minifier-terser'
const minification_options = {
collapseWhitespace: true,
collapseInlineTagWhitespace: true,
removeComments: true,
ignoreCustomComments: [/^#/],
minifyCSS: true,
minifyJS: true,
sortAttributes: true,
sortClassName: true
}
export async function handle({ event, resolve }) {
const response = await resolve(event, {
transformPageChunk: ({ html }) => minify(html, minification_options)
})
return response
} Put this code to I'm using this with package.json {
"devDependencies": {
"@sveltejs/adapter-static": "^1.0.0-next.43",
"@sveltejs/kit": "next",
"html-minifier-terser": "^7.0.0",
"svelte": "^3.50.1",
},
} |
Beta Was this translation helpful? Give feedback.
-
Comment #2947 (comment) works for me. This should be probably be updated https://kit.svelte.dev/docs/migrating#integrations-html-minifier |
Beta Was this translation helpful? Give feedback.
-
Just saw this option too https://github.com/ntsd/sveltekit-html-minifier that seem perfect for the job ! |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Is it possible/recommended to use something like html-minifer on Svelte files during the compilation step?
When I build a SvelteKit project, that is, when I run
npm run build
and then take a look at the generated files, I see a lot of redundant whitespace characters in the final output that are just unnecessarily adding to the file size. These are whitespace characters that were originally in my.svelte
files only for formatting purposes.So, for example, I have a
Button
component, that looks like this:What's relevant here is the line-breaks and spaces in the
class
attribute.Now, here's the equivalent generated file:
So, my question is: Is it possible to use an HTML minifer on
.svelte
files in SvelteKit to get rid of all this? And also is it usual or recommended or not?Update: I just took a quick look at SvelteKit's migration guide and the last section there talks about HTML minifer, and it's recommending we use a hook, but that sounds crazy to me, because unless I'm missing something, by using a hook to minify the HTML you're running the HTML minifer on EVERY SINGLE REQUEST. Isn't that terribly inefficient?! If your HTML is large enough it can effectively result in a worse performance than if you had just served the unminified HTML.
Besides, this doesn't fix the problem of unnecessary whitespace in the JS files.
Thank you.
Beta Was this translation helpful? Give feedback.
All reactions