3

I have tried to set up some global Scss in my Gatsby application, but it looks like after doing this i am seeing some odd behaviour in dev tools:

u

You can see that my global styles are appearing and being overwritten multiple times.

It is a Gatsby app so i am using sass-loader and the default dart-sass.

Here is how i have configure my gatsby-config.js file to allow me to use these global styles based on this stackoverflow post: https://stackoverflow.com/a/65904094/12119984

module.exports = {
  plugins: [
     ...
    {
      resolve: `gatsby-plugin-sass`,
      options: {
        additionalData: `@use 'main' as *;`,
        //allow mixins, variables etc to be accessible globally
        sassOptions: {
          includePaths: [`${__dirname}/src/styles/sass`],
          // data: `@import "main.scss";`,
        },
      },
    }...

I the use @forward along with @extend to get it all working in my module.scss files. My folder structure looks like this:

enter image description here

My global styles are in base.scss and I import them into main.scss using @forward:

@forward "base";
@forward "layout";
@forward "components";

As an exmaple, here is my index.module.scss file where i then use these global styles:

.sectionHome {
 ...
  h1 {
    background-color: $color-secondary;
    @extend .uMarginBottomLarge;
    @extend .headingPrimary;
  }
}

It seems like a reasonable approach to me to use some global styles but to extend them into local sccs module classes, so can anyone explain to why these global styles are being applied several times?

Sean
  • 587
  • 4
  • 20

1 Answers1

0

The @forward rule, according to the docs:

The @forward rule loads a Sass stylesheet and makes its mixins, functions, and variables available when your stylesheet is loaded with the @use rule. It makes it possible to organize Sass libraries across many files, while allowing their users to load a single entrypoint file.

So basically, each time you are requesting a CSS module in some component, you are importing all the nested extensions (@extend and @use). Moreover, because of React's component extensions, you may also nest styles when importing nested components (Button in Layout, Layout in a index.js, etc)

Global styles in CSS apply exactly in the same way as CSS "standard" files, as you can see in Gatsby's docs, extending its documentation, you will need to add the following in your gatsby-browser.js:

import "./src/styles/sass/main.scss"
Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67