Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same CSS is injected into HTML over and over again

Tags:

webpack

I am using webpack to load my SCSS files, but I see the CSS being repeated many times over in my HEAD section in the HTML.

I use sass loader and postcss

Any ideas?

enter image description here

like image 364
Tarlen Avatar asked Dec 18 '22 14:12

Tarlen


1 Answers

I suspect you use different SCSS files you import all over your app. Do you import globals in those SCSS files? Something with common styles like fonts and base variables etc? If yes, you need to split them up.

If you use SASS/SCSS with webpack, you really have to make sure that everything you import does not output CSS, because it will not be deduplicated.

See this example:

index.js

import './header.scss';
import './button.scss';

header.scss

import 'base';

.header { color: hotpink; }

button.scss

import 'base';

.button { font-size: 14px; }

_base.scss

@import url(http://fonts.googleapis.com/css?family=Roboto);

The result of the above four files with webpack and sass-loader will be that the Google Fonts import is included twice. All SASS imports you do that point to another SASS file are not handled by webpack, so they are not deduplicated. We had this issue too in a large codebase but managed to fix it.

What you want to do instead is the following:

index.js

import './global.scss';
import './header.scss';
import './button.scss';

header.scss

import 'varsandmixins';

.header { color: hotpink; }

button.scss

import 'varsandmixins';

.button { font-size: 14px; }

global.scss

// This file should include everything you need globally that outputs CSS.
@import url(http://fonts.googleapis.com/css?family=Roboto);
@font-face {
    // your font definition here
}

_varsandmixins.scss

// This file on it's own should not output any CSS! Only variables and mixins!
$baseColor: #000;
$fontFamily: 'Roboto', sans-serif;
@mixin something($var) {
    rule: $var;
}

You can see in the example above that the contents of global.scss are only imported via JS, so they go through webpack and will be deduplicated. All imports done from inside a SASS context don't output any CSS, so there's no issue with duplicate CSS either.

In short: when using sass-loader with webpack, try to do as much importing in JavaScript. Only imports done in JS can be deduped by webpack. Imports done from inside SASS files should only import variables, mixins and other things that don't output any CSS.

like image 73
Ambroos Avatar answered Jan 02 '23 16:01

Ambroos