I have the following project structure:
gatsby-config.js
/src
/components
layout.jsx
/button
button.jsx
button.scss
/pages
/styles
styles.scss
_mixins.scss
_variables.scss
and gatsby-config.js
and styles.scss
are configured respectively in the following way:
...
plugins: [
...,
`gatsby-plugin-sass`
]
...
@import 'variables',
'mixins';
in order to access the mixins and variables, the styles.scss
is being currently imported in all the components' scss files, e.g.:
//button.scss
@import './../styles/styles.scss'
This approach is working, but the problem is, as the project grows, the styles.scss
is being imported multiple times and seems to be something wrong with this approach.
Is it possible to import styles.scss
only once, and make all mixins and variables available across all the components?
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.