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

Having trouble getting the map function to work in ReactJs while using Next.js?

Hey there, I am diving into ReactJS with the "Nextjs" framework and working on fetching data using async functions. However, I am facing an issue where I am unable to fetch data using the map function. The console.log is displaying a message saying "item ...

The transformation from className to class attribute does not occur for custom elements in JSX

I recently encountered an issue with one of my React components where the "className" attribute was being converted to "classname" in the resulting HTML, instead of the expected "class" attribute. The component had a custom element definition as follows: ...

As a React developer, it's essential to understand how to trigger a callback event in a child

Hello there, I am just starting out with React and currently utilizing Fluent UI in my project. My aim is to create a reusable Panel component using Fluent UI. Below is the code snippet I have been working on: import * as React from 'react'; impo ...

What is the best way to vertically align Bootstrap Columns to ensure they have consistent heights?

I'm currently in the process of building a website that features multiple images and content organized into columns using Bootstrap as the framework. I'm wondering if there's a way to automatically adjust all the columns to the height of th ...

Adjust the value of a cell in the MUI Data Grid in real-time

In the Data Grid, there are 9 columns including "Rate" and "Transfer". There is also a column labeled "Total" which should display the multiplication result of "Rate" and "Transfer", adjusting with any changes made to the "Transfer" cell value. The "Transf ...

Stepper that is vertical combined with table information

I am currently facing a unique challenge with a component I'm trying to create. It's a combination of a vertical Stepper and a Datagrid. My goal is to group specific table sections within the content of a vertical Stepper, purely for data visual ...

Is it possible to populate a ReactJS TreeView with a JSON/array of objects using Material UI?

My data structure consists of an array of objects with values to be displayed in the <TreeView> component: const treeItems = [ { id: uuidv4(), name: 'English', children: [ { id: uuidv ...

What are the steps to achieve such a design?

Can you show me how to create a single layout using HTML and CSS? I am struggling with splitting the screen properly. Could you provide a simple example, maybe on jsfiddle? https://i.stack.imgur.com/d2rbn.jpg Thank you in advance! EDIT: I have added a ...

Is it possible to copy text from an iframe to the clipboard?

I have encountered an issue in my React app where I am trying to copy text from a card when the user clicks on it. The app displays multiple cards by looping through an array, so there can be any number of cards (n). The problem arises because the React a ...

Tips for sorting through existing data without resorting to a remote call - Material Table repository by mbrn (mbrn/material

Currently I am using the mbrn/material-table library which includes filtering on a column and remote data feature. However, when I apply a filter term, the table sends an API call to the server with the filter criteria in the query object. My desired outco ...

Deploying the in-house API to operate on a publicly accessible domain

After completing tutorials on e-commerce MERN Stack by Lama Dev, I am ready to deploy my website. While I have successfully deployed the client side on Hostinger hosting using my domain, I am facing difficulties with the API which only works locally. I am ...

The server is failing to route the Django resource correctly, resulting in an error message "Failed to load resource: the server responded with a status of 404 (Not Found) main.7ec538f6.chunk.js:1"

During my web development project, I encountered an issue with serving React build files through Django. While the React build files were functioning correctly on their own, they were not being served properly by Django. This problem arose when changing ...

What is the best way to globally install all necessary packages and dependencies?

Every time I create a new React app, a node_modules folder is generated with numerous packages under the app/project directory. If I create multiple apps, each one will have its own node_modules folder with thousands of packages. This leads to redundant no ...

Instructions on how to automatically navigate to a different tab upon clicking an <a> element on a separate webpage, and subsequently display the designated tab on that

I have a button on my home page that, when clicked, should open a specific tab section on another page. The button is located on one page and the tabs are on a different page. On the second page, I have multiple tabs but will only mention one here, which ...

Is the return value of cache.readQuery in Apollo a copy of the data?

While studying the mutation documentation, a question arose regarding whether cache.readQuery returns a copied version of the data? For example: const { todos } = cache.readQuery({ query: GET_TODOS }); // Do I need to create a copy first, or is it alrea ...

The Material UI Multiple Select is not displaying all of the selected items, which may be due to a CSS problem

Having trouble with the Multiple Select? When selecting multiple items, they aren't visible because the height isn't sufficient to display all selected options. I experimented with adding height:auto in the Chrome console and it solved the issue ...

Guide on Modifying the CSS File of an Installed Plugin on WordPress

I am looking to customize the design of a WordPress plugin by editing its CSS file. When trying to locate the CSS file of the installed plugin through Plugins --> Installed Plugin --> Editor, I could only find .php files instead of the desired CSS file. ...

Having trouble publishing project on Vercel because of a naming issue

Whenever I try to deploy a project on vercel, I encounter an error stating that the project name is not valid. The specific error messages are as follows: Error: The name of a Project can only contain up to 100 alphanumeric lowercase characters and hyphe ...

You cannot edit FabricJS IText (and Textbox) within the context of React Bootstrap

I'm having trouble incorporating a canvas into my React Bootstrap component. Specifically, I am encountering issues with the text editing functionality when using IText and Textbox. Despite setting the corresponding properties, I am unable to modify t ...

React.js with Typescript is throwing an error stating that a property does not exist on the child component

Currently, I am working with React in conjunction with typescript 2.3.4. I keep encountering the error TS2339: Property 'name' does not exist on type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'. This issue arises when attemptin ...