Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Svelte: Unable to get imported unused CSS purged

I unsuccessfully tried to remove unused css imported from an external css file.

I have tried a lot of combinaisons in vain, every time I run the build script I end up with a huge bundle.css.

Here is the list of everything I tried so far:

  • Importing the file from App.svelte <script>
  • Importing the file from App.svelte <style> (using postcss-import)
  • Importing the file directly from main.js
  • Using postcss-purgecss along with rollup-plugin-postcss instead of passing by svelte-preprocess

I am pretty sure there is something I am doing wrong but I honestly cannot figure out what.

If anyone have a clue on how to resolve this I would love to hear some feedback.

Simple repo example: https://github.com/mgrisole/svelte-playground

like image 319
Maxime Grisole Avatar asked Oct 30 '25 08:10

Maxime Grisole


1 Answers

You need to follow these steps:

  1. Import rollup-plugin-postcss in rollup.config.js:
import postcss from 'rollup-plugin-postcss';
  1. Replace relevant section (lines 41-56 of your rollup.config.js) with:
svelte({
  preprocess: sveltePreprocess({ postcss: true }),
  compilerOptions: {
    dev: !production,
    css: css => { css.write('bundle.css') },
  },
  ...(production && { emitCss: false }),
}),
production
  ? postcss({ extract: true, minimize: true })
  : css({ output: 'bundle.css' }),
  1. Configure purgecss in postcss.config.js:
const purgecss = require('@fullhuman/postcss-purgecss')({
  content: ['./**/**/*.html', './**/**/*.svelte'],
  whitelistPatterns: [/svelte-/],
  defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []
});

const isProduction = !process.env.ROLLUP_WATCH && !process.env.LIVERELOAD

module.exports = {
  plugins: [
    ...(isProduction ? [purgecss] : [])
  ]
};
like image 111
mutil Avatar answered Nov 02 '25 22:11

mutil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!