Search code examples
reactjssassvite

Avoid class duplications while importing global SCSS


I am building a new ReactJS project with Vite and using scss for stying. I have colors, fonts, etc. classes that are forwarded from one _index.scss file.

@forward 'colors';
@forward 'constants';
@forward 'typography';
@forward 'alignment';
@forward 'common';

I need to use these classes for each component's individual scss. When I use @use to import that index class. Importing like this and my project works properly.

@use '/src/styles';

However, I see duplicated classes on developer tools for each component that is used on the page.

I want to use these classes from every other scss file but don't want them to duplicate. Looking for a while but I couldn't find a proper solution.

I have tried to use import and also tried to use configure vite to import certain files to avoid this but it is still duplicated. I also added it into app.js but it didn't work. I researched and couldn't find a well-explained solution.

Thanks


Solution

  • If your partials include non-placeholder selectors, then all of these selectors will be included in the files where you import (use/forward) them. So for example if you have two components, each of them importing its own style file, which in turn imports the partials: you get the duplicate selectors.

    If you want to have global classes, then you should only import them once, in your entry component file. And if you also need to import variables, mixins, functions, etc, you should use separate partials.

    For example:

    src/
    └── styles/
        ├── non-selectors/
        │   ├── _variables.scss
        │   ├── _mixins.scss
        │   └── index.scss
        ├── global-selectors/
        │   ├── _common.scss
        │   ├── _typography.scss
        │   └── index.js
        └── App.jsx
    

    On the index style files:

    // src/styles/non-selectors/index.scss
    
    @forward 'variables';
    @forward 'mixins';
    
    // src/styles/global-selectors/index.scss
    
    @use 'common';
    @use 'typography';
    

    On your entry component file:

    // App.jsx
    
    import "./styles/global-selectors/index.scss";
        
    const App = () => {
      // ...
    };
    
    export default App;
    

    And on any component needed the variables, mixins, etc:

    // MyComponent/styles.scss
    
    @use '/src/styles/non-selectors';