Guide on customizing webpack to incorporate SCSS in a React application

After creating my React app using create-react-app (with React ver. 16.6.3), I decided to incorporate SCSS into my components. To begin, I ran the eject script and made necessary adjustments in webpack.config.dev.js:

{
   test: cssRegex,
   exclude: cssModuleRegex,
   use: getStyleLoaders({
          importLoaders: 1,
           modules: true,
           localIdentName: '[name]__[local]__[hash:base64:5]'
        }),
}

Additionally, I installed the node-sass package.

Next, I created a .scss file named Test:

.Test {
  background-color: gold;
  .Header {
    color: lighten(purple, 20%);
  }
}

I then developed a Test component that imported this .scss file:

import React from 'react';
import style from './test.scss';

const Test = (props) => (
  <div className={style.Test}>
    This is div1
    <div className={style.Header}>Div 2</div>
  </div>
);

export default Test;

However, when I tried this approach, the styling did not apply as expected. As an alternative, I attempted importing the .scss directly:

import './test.scss';

...
<div className='Test'>
  This is div1
  <div className={style.Header}>Div 2</div>
</div>
...

This method seemed to work fine and displayed the styling on the div with the className of 'Test'.

In an effort to tweak the webpack configuration, I made the following adjustments:

const CSSModuleLoader = {
  loader: 'css-loader',
  options: {
    modules: true,
    sourceMap: true,
    localIdentName: '[local]__[hash:base64:5]',
    minimize: true
  }
}

...

{
  test: /\.scss$/,
  exclude: /\.module\.scss$/,
  use: ['style-loader', CSSLoader, postCSSLoader, 'sass-loader']
},
{
  test: /\.module\.scss$/,
  use: [
    'style-loader',
    CSSModuleLoader,
    postCSSLoader,
    'sass-loader',
  ]
},

Initially, I encountered an error stating autoprefixer not defined, which I resolved by importing it with

const autoprefixer = require('style-loader')
. However, I am uncertain if this was the correct solution.

Subsequently, I faced the following error message:

Invalid configuration object...

At present, I'm unsure how to proceed with resolving this issue...

Looking for guidance on configuring webpack to either compile .scss files to .css directly in the same directory for immediate usage or to utilize .scss imports in the development phase and subsequently compile them to .css for production?

Answer №1

Below are the rules to be utilized in the webpack file, eliminating any unnecessary code.

rules: [
      {
        test: /\.s?css$/,
        use: [
          'style-loader',
          'css-loader',
          'sass-loader'
        ]
      }
    ]

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

Enabling authentication in a ReactJS application integrated with Google Cloud Functions and Cloud Run: A step-by-step guide

I am in the process of developing a reactJS application that will be launched in a web browser. My goal is to send requests from this application to services running on Google Cloud Run and Google Cloud Functions, both of which have authentication enabled. ...

What is the best way to align this div tag with the right side of the box?

.left { width: 50%; display: inline-block; float: left; } /* Second user block */ .right { border-color: lightskyblue; background-color: darkcyan; width: 50%; ...

Some pages are missing on the redirected website hosted on Firebase

I have a React application hosted on Firebase and I purchased a custom domain www.encor.cc in order to deploy my app on that URL. However, even after redirecting my custom domain (encor.cc) to the Firebase deployed web URL (adripa-4771c.web.app), the encor ...

Is it possible to nest an array within a value of a Sass object?

I'm currently attempting to incorporate an array within the value of an object. $background-things: ( 'a': ['100vh', 'transparent', 'column'], 'higher': ['70vh', '#000', &ap ...

Overlap one element entirely with another

Currently, I am working on a way for an element called overlayElement to completely cover another element known as originalElement. The overlayElement is an iFrame, but that detail may not be significant in this scenario. My goal is to ensure that the over ...

Utilize the tree element provided by syncfusion in conjunction with Material UI

Currently, I am in the midst of a project that utilizes Material UI. However, I have come across an obstacle when trying to locate a checkboxes tree within Material UI. Surprisingly, I stumbled upon one in Syncfusion. Is it acceptable for me to solely im ...

Ways to enhance widget titles with borders on Blogger

As a Blogger user, I am looking for guidance on how to add a border around the title of each widget/gadget. When I place widgets such as About Me, Follow Us, etc., in my sidebar, I want them to have borders like in this image. While I know how to customize ...

What causes a neighboring div to change width when a multi-line span is present?

Here is my React code: <InfoWrapper> <InfoCircle> <span>i</span> </InfoCircle> <span className="info-label"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. elit. </span> </InfoWrap ...

Having trouble with implementing Entering Animations in React Native Reanimated 2

Trying to incorporate the entryAnimations feature from The documentation makes it appear straightforward, but upon running the following code, nothing happens: ... import Animated, { AnimatedLayout, FadeInRight } from "react-native-reanimated"; ...

reactjs function continually returning undefined

My approach is rather simple. It involves iterating through an array of objects and retrieving the object with the specified id in the parameter. Here's how it looks: returnValueToDelete(id) { this.state.rows.map(function(value) { if (value ...

When trying to click the button in Navbar.jsx, I encounter an error when attempting to invoke the setShowCart(true) function

I've encountered an issue while trying to call the setShowCart(true) function in Navbar.jsx. I'm unsure of how to fix this. import React from 'react' import Link from 'next/link'; import {AiOutlineShopping} from 'react-ic ...

Adjust the dimensions of the initial cell

I need to adjust the size of the initial "generated" cell in a grid. The grid is not present in the HTML markup until JavaScript prints RSS information on it, making it difficult to target specific rows or cells directly. Note: The first element is hidden ...

"Utilizing Material UI's Stack component for a responsive, full-width

Is there a way to achieve full width for Item 2 without using width:100% with flexbox? <Box sx={{ width: '100%' }}> <Stack spacing={2} alignItems="flex-start"> <Item>Item 1</Item> <Item>Item 2< ...

Incorporate a background image into input fields with Autofill on mobile browsers to override the default yellow background that obscures them

It is common knowledge that modern browsers apply a less than appealing yellow background to text fields when Autofill is used by visitors. A helpful workaround is known to override the default text and background colors, and even incorporate a background ...

Don't pay attention to CSS that is outside of the div

Currently, I am attempting to populate a div with templates in order to preview them. These templates are sourced from a database and configured using php. My issue lies in the fact that certain entries consist of entire websites (complete with a head and ...

The error message "Cannot read property 'match' of undefined (evaluating 'global.navigator.userAgent.match')" is occurring in a React

I recently downloaded a Time picker from react-times -npm (found the source code on github) After running the app, I encountered a syntax error stating "Undefined is not an object (evaluating 'global.navigator.userAgent.match)". I'm having troub ...

Issues arise when attempting to use Axios and Express within a React App, resulting in a "Cannot POST /" error

I am currently working on setting up a basic form to send emails, but I keep encountering the following error: Error: Cannot POST / The structure of my App.js file using Create React App is as follows: import React, { Component } from 'react'; ...

Tips for including and excluding personalized Chips from input

Just started learning React/typescript, any assistance would be greatly appreciated Custom Chip (CC.chip) is a specialized Chip UI component that can be utilized as demonstrated below. const [isOpen, setIsOpen] = useState(true); const onClose = Re ...

A guide on developing a component within a personalized hook to manage state internally

Is it possible to create a component within a custom hook that manages the state for that component? I attempted to do this, but I encountered an issue with drag-and-drop functionality. It seems that instead of dragging the slider, it only changes value o ...

Arranging five divs within one main div horizontally with equal margins between them

I am currently working on a website system where I need to place 5 divs within 1 main div horizontally. However, I want the spacing between the 5 divs to be equal and fixed within the main div. Below is how my current page looks: https://i.stack.imgur.com ...