Is it advisable to use only one base SCSS @use import throughout the entire React application?

Hey there, I've got a question that's been on my mind. I really enjoy using SCSS in React, but for the longest time, I steered clear of variables and mixins because dealing with imports after making changes was a complete nightmare for me (I had a separate SCSS file for each component).

But then I stumbled upon a solution - I could easily create absolute paths in React imports like this:

import "src/scss/variables"

Now, I'm back to feeling excited about exploring all the amazing features SCSS has to offer.

So here's my question - can I create a single global.scss file and use only this file throughout my whole app when importing styles into different SCSS files? For example, the global.scss file would have contents similar to this:

@use "variables"
@use "mixins"
@use "functions"

@forward "variables"
@forward "mixins"
@forward "functions"

And in the components.scss file, I would simply import it like this:

@use "src/scss/global"

.test {
  background-color: global.$primary-color;
}

Another thing I'm curious about is whether it's possible for these globals to be imported just once in the main.jsx or app.jsx files and then automatically utilized in all other files within the project?

Answer №1

If you want to consolidate all your variables, mixins, and functions into a single file, you can achieve that easily. The approach you mentioned is on the right track, but remember to use @forward instead of @use:

@forward "variables";
@forward "mixins";
@forward "functions";

Ensure that these three files are declared as partials.

Importing the global.scss file directly in your .jsx file may be unnecessary since it contains no styles. However, you can configure your bundler to automatically include it in all your .scss files.

For instance, if you are using webpack with sass-loader, utilize the additionalData option:

options: {
  additionalData: "@use 'src/scss/global';"
}

In case you encounter an error related to an @import loop, exclude the global style files to prevent automatic importing:

options: {
  additionalData: (content, loaderContext) => {
    const { resourcePath, rootContext } = loaderContext;

    // Define the path where your global files reside
    const styleGlobalPathRegex = /^src\\scss\\.*/;

    const relativeFilePath = path.relative(rootContext, resourcePath);
    const isAGlobalStyleFile = relativeFilePath.match(styleGlobalPathRegex);

    return isAGlobalStyleFile ? content : "@use 'src/scss/global';" + content;
  };
}

For users of Vite, incorporate it by utilizing css.preprocessorOptions:

css: {
  preprocessorOptions: {
    scss: {
      additionalData: ...
    }
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Printing from a Windows computer may sometimes result in a blank page

Looking to incorporate a print button into an HTML page, I'm facing an issue. The majority of the content on the page should not be included in the printed version, so my approach involves hiding everything in print and then showing only the designate ...

What are the best techniques for organizing SCSS in Next.js?

There are multiple pages with some unused items. Is there a method to search and delete all the items based on their classname? Appreciate any assistance you can provide! ...

The issue of sluggishness in Material-UI when expanding the menu is causing delays

Watch Video Having trouble with the behavior of the Menu opening and closing similar to this example. The text seems slow to change position. Any ideas why? This is the devDependencies configuration I am using in webpack. "devDependencies": { ...

Could my state be changing? If it is, what can I do to fix it?

Recently, I've been working on a simple component that constructs a list of reports from an array of objects. I've managed to implement filter and sort functionality, but I'm encountering an issue where the sort functionality works fine, yet ...

Encountering a TypeError in NextJs apps when using next-i18next: NextI18Next seems to be unrecognized as

I am currently in the process of creating a multi-language website using next.JS and the next-i18next package. I have transitioned my project from i18next to next-i18next. The server is up and running at http://localhost:3000 I am encountering an error t ...

Transforming functions into a new typed object with different function signatures

I am currently updating some React/Redux code that previously followed an older pattern to a more modern "hooks" based approach, using TypeScript. In the old pattern, we utilized "class-based" components and passed their "dispatch" functions using mapDisp ...

How to pass a single value using onClick event without relying on form submission

I prefer to pass a single value instead of multiple putPriority fetch calls. This value will not be inputted by the user directly, but rather passed through an onClick event. For example, I want the onClick to send a specific number to "status" in the fe ...

Curious about how to utilize Gridfs to upload files or videos larger than 16mb with the help of express, mongoose, and mongodb?

I'm encountering an issue with my code. It works fine for uploading images, but when I try to upload videos or files larger than 16mb, it fails. I am a beginner and seeking help on what to do next. const Freecoursevideo = require("../models/freec ...

Tips for creating a sleek and modern MUI table with a dark theme

I am struggling to create a dark theme for the Table component from MUI. I attempted to use styled() and the sx prop to customize the appearance, but unfortunately, both methods failed to produce the desired dark theme. The table currently looks quite unsi ...

Display the CSS dropdown menu as a block`

I've been attempting to design a dropdown menu. My goal is for the anchor tag to display when hovered over. I understand that using display:block won't work when the 'a' is not part of the block, but I'm unsure how to proceed. Any ...

Removing the active class from a Bootstrap menu can be achieved by targeting the specific

I have successfully implemented a Bootstrap Menu by placing it in a separate header.html file and using the php include function to call that file on every page of my website. However, I am now trying to figure out how to dynamically change the active cl ...

Why does the Google Tag Manager noscript tag show up as a string when using react-gtm-module?

Implementing Google Tag Manager Tags in a React/Next.js app hosted on Netlify, I used the react-gtm-module. While the gtm script tag in the head section works perfectly, the noscript tag in the body is displaying an iframe as a string: <body> < ...

Disable the use of componentWillUnmount in case of an incomplete form

I have implemented a form using redux-form and I am trying to set up a scenario where if any of the form's inputs have content and the user tries to navigate away from the page, a prompt should appear. My goal is to prevent the page from being unmoun ...

Using React Router and Flux for automated redirection in a programmatic manner

Currently immersed in a project leveraging NodeJS, Express, Flux and React, with the added use of React Router for client-side routing. It appears I might be misunderstanding how the process should ideally function. My present goal is to redirect users to ...

Create personalized styles for each item within a stack with specific spacing using the @mui library

Is there a way to change both the background color and spacing area when hovering over each item in my list? https://i.stack.imgur.com/87TST.png <Stack spacing={4} divider={<Divider variant={`fullWidth`} orientation={`horizontal`} flexItem/>}> ...

Tips and tricks for stopping a jquery animation

I have created a hover effect for list items. When I hover over an item, it triggers an animation using the .animate() method. However, when I move my cursor away from the item, the hover animation continues until it reaches its end point. Is there a way ...

Attempting to highlight a specific list item by using the CSS current class to emphasize its active state

I've been experimenting with different solutions I found in previous questions, but unfortunately, none of them have worked for me. I suspect the issue lies in the fact that the element is deeply nested within CSS classes, and my lack of experience is ...

Typescript is throwing an error when trying to use MUI-base componentType props within a custom component that is nested within another component

I need help customizing the InputUnstyled component from MUI-base. Everything works fine during runtime, but I am encountering a Typescript error when trying to access the maxLength attribute within componentProps for my custom input created with InputUnst ...

Personalize the appearance of material UI Switch when it is both checked and disabled

Struggling with applying styles to a Material UI Switch component in React when it's disabled. I've attempted to use withStyles for this purpose, and while the styling for checked vs unchecked states and the track are working fine, I can't s ...

Navigating through complex routes was tricky in Next.js 14 due to the error 404 on hard navigation with

While working on implementing tab groups using Parallel Routes in Next.js 14, I encountered an issue where a 404 page only appears during hard navigation to /gnb/mypage/tab1. The tabs and their navigation function properly on initial render and when switch ...