When I included Bulma CSS my css bundle size increased up to 1MB, which is quite large for a website. After purging unused css I was able to reduce the bundle size close to 140KBs which is much more acceptable. In this post I will describe the way I did it :)
Adding required dependencies
npm i @fullhuman/postcss-purgecss postcss-load-config
Create the postcss.config.js file at the root of your project. This will instruct postcss-purgecss how to do its job.
const purgecss = require("@fullhuman/postcss-purgecss")({
content: ["./public/**/*.html", "**/**/*.svelte"], //filtering all svelte
whitelistPatterns: [/svelte-/, /fa-icon/], //Svelte compiler adds these prefixes. We won't mess with it!
defaultExtractor: (content) => content.match(/[A-Za-z0-9-_:/]+/g) || [],
})
const dev = process.env.ROLLUP_WATCH
module.exports = {
plugins: [...(!dev ? [purgecss] : [])], //We are only purging in prod builds
}
The above postcss.config.js file will be loaded automatically by the postcss-load-config plugin. There we include all svelte files and index.html file to purge css plugin so it can analyze the css usage and remove unused css from the bundle. We want to keep all css classes that the Svelte compiler prefixes so we can include it in the whitelistPatterns
option. Rest is self explanatory.
Finally itβs time to tell rollup to incorporate purgecss plugin using svelte-preprocess.
...
svelte({
preprocess: sveltePreprocess({
defaults: {
style: 'scss',
},
scss: {
//Customize bulma colors
prependData: `@import 'src/styles/variables.scss';`,
},
postcss: production // To enable purging unused css
}),
We are loading Bulma CSS using the variables.scss file and we enable postcss in the sveltePreprocess plugin in production mode. So thatβs pretty much it!
Top comments (0)