Include sass in gatsby globally
Providing SCSS variables globally to your components
- With
@use
- SCSS syntax
- gatsby-plugin-sass
- Component-Scoped Styles with CSS Modules
gatsby-plugin-sass config
gatsby-config.js
file:
{
resolve: `gatsby-plugin-sass`,
options: {
implementation: require("sass"),
data: `@use "${__dirname}/src/global-styles/variables" as var;`
}
},
var
will be used as namespace.
Providing variables to your scss files
./src/global-styles/_variables.scss
./src/components/main.jsx
./src/components/main.module.scss
Info about the underscore in _variables.scss
, partials.
_variables.scss
file:
$color-1: red;
$color-2: blue;
main.jsx
file:
import React from 'react'
import style from './main.module.scss'
const Main = () => (
<div className={style.main}>Content</div>
)
export default Main
main.module.scss
file:
.main {
color: var.$color-1;
}
But I need expose some global styles in gatsby-browser.js
Well, your are going to need @use
, or follow other answers that use @import
in gatsby-config.js
. Mixing @import
and @use
may not work because of:
Heads up!
A stylesheet’s @use rules must come before any rules other than @forward, including style rules. However, you can declare variables before @use rules to use when configuring modules.
https://sass-lang.com/documentation/at-rules/use
I stopped using @import
, only using @use
.
global-styles.scss
file:
@use "./variables" as var;
body {
color: var.$color-2;
}
gatsby-browser.js
file:
import './src/global-styles/global-styles.scss'
As Ankit Sinha mentioned, you can import your styles in gatsby-browser.js
:
import './src/styles/styles.scss';
This method is mentioned in the Gatsby tutorial.
According to the docs (see Standard Styling with Global CSS Files):
The best way to add global styles is with a shared layout component.
Your project structure suggests that you are using one (layout.jsx
). If that's the case, you can also import your styles in layout.jsx
:
import './../styles/styles.scss';
You are able to pass options to Sass via gatsby-plugin-sass
.
The following options would globally expose the contents of ./src/styles/_styles.scss
to each Sass file in the project, without the need to explicitly import it.
module.exports = {
plugins: [
{
resolve: 'gatsby-plugin-sass',
options: {
data: `@import "${__dirname}/src/styles/styles";`,
}
},
],
}
Note: The below might be obvious to some but it's worth mentioning for future readers.
Only do this with Sass files that contain just variables, mixins, functions, etc (Sass features that do not output any actual CSS until they are consumed). Otherwise you will end up with CSS that is repeated multiple times across your project.
Example repo
Create a file named gatsby-browser.js
in the root of your directory. Import the .scss
file once and it will work perfectly .
In your gatsby-browser.js
import "./src/styles/styles.scss"