4

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:

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

peterh
  • 11,875
  • 18
  • 85
  • 108

1 Answers1

3

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] : [])
  ]
};
mutil
  • 3,205
  • 1
  • 27
  • 34
  • Thank you very much for your quick reply, unfortunately I end up with a nearly empty bundle.css after executing the build script. I created a branch following your suggestions, do you know if I omitted something: https://github.com/mgrisole/svelte-playground/tree/alternative-conf – Maxime Grisole Jan 15 '21 at 01:51
  • 1
    You should remove or comment out `css({ output: 'bundle.css' })` (line 56). This is handled now in line 52, which runs only on dev mode. – mutil Jan 15 '21 at 11:13
  • Indeed, that was so obvious, thank so much mutil for your precious help! – Maxime Grisole Jan 15 '21 at 14:05
  • I think we should change whitelistPatterns to safelist it seems like it has been changed since v3 https://github.com/FullHuman/purgecss/releases/tag/v3.0.0 It seems however that it is not needed, if I remove the exception svelte's selectors are not being removed. It surely need more investigation on my side though. – Maxime Grisole Jan 15 '21 at 19:08