How to import scss files and use them globally in a React application?

Viewed 3885

I have my React application structures like this:

-src
|-components
 |-Card.js
 |-Card.scss
 |-Navbar.js
 |-Navbar.scss
|-styles
 |-_mixins.scss
 |-_variables.scss
|-App.js
|-App.scss

I use node-sass so for component-x I just need to import component-x.scss to apply the scss file. However I have the _mixins.scss and _variables.scss which I need to use on everywhere, I cannot import them in each scss file. How can I import these files globally so I could use them anywhere I want?

2 Answers

Create a main.scss and import all inside!

There is an example with your files:

/********************************SASS MAIN***********************************/
//COMPONENTS
@import "components/card";
@import "components/navbar";

//STYLES
@import "styles/mixins";
@import "styles/variables";

Then in your App.js just import 'main.scss'

more info about import in sass here

you can use customize-cra with react-app-rewired and in you config-overrides.js


const { override, adjustStyleLoaders } = require("customize-cra");
const path = require("path");

module.exports = override(
  adjustStyleLoaders((loader) => {
    loader.use[1].options.additionalData = `@import "./src/assets/scss/_variables.scss";`;
  })
);

and change your package.json scripts into

  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-scripts eject"
  },

Related