Using variables from global sass stylesheet inside a sass module
I think that the best practise is to have a global .scss
file, with all the basic styles (like primary color etc.).
Then, for each React Component, you write it’s own module, to keep it clean and the .css
needed to import to a minimum.
Using this approach, I get a weird error though.
I have a styles/global.scss
file with this:
$primary-color: #6dd3d6; body { margin: 0; padding: 0; }
now I have another file called NavBar.module.scss
with this content:
@import "styles/global"; .nav { display: flex; padding: 20px; background: $primary-color; }
My _app.js
file:
import React from 'react'; import '../styles/global.scss' export default function App({ Component, pageProps }) { return <Component {...pageProps} /> }
and my NavBar.js
file:
import React from 'react'; import styles from './NavBar.module.scss'; export default function NavBar() { return( <nav className={styles.nav}> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> </nav> );
}
This gives me the following error:
./components/NavBar.module.scss:3:1 Syntax error: Selector "body" is not pure (pure selectors must contain at least one local class or id) 1 | $primary-color: #6dd3d6; 2 | > 3 | body { | ^ 4 | margin: 0; 5 | padding: 0;
You can’t use body
selector in a module as it says in the error message: "Selector "body" is not pure (pure selectors must contain at least one local class or id)".
Create another Sass file that contains only variables and import it in the module / global Sass files.
Edit from Question Author to provide additional information:
It is also wrong to import the global.scss
in any of the .module.scss
classes, which caused the error. It is a global style, no need to reimport it.