Transitioning from Webpack version 4 to version 5 resulted in a failure to detect certain styles

After migrating my React project to Webpack v5, I am facing an issue where none of my .scss files are being picked up when I run the project.

I meticulously followed the guide on migrating webpack https://webpack.js.org/migrate/5/, updated all plugins and loaders (which were MAJOR updates), and adjusted the configuration file to fit the new versions. However, the styles are not being applied.

Here is a snippet from my package.json:

  "devDependencies": {
    ...
    "clean-webpack-plugin": "^4.0.0",
    "compression-webpack-plugin": "^10.0.0",
    "copy-webpack-plugin": "^11.0.0",
    "css-loader": "^6.7.1",
    ...
    "file-loader": "^6.2.0",
    "fork-ts-checker-webpack-plugin": "^6.2.6",
    "html-webpack-plugin": "^5.5.0",
    ...
    "mini-css-extract-plugin": "^2.6.1",
    ...
    "node-sass": "^4.14.1",
    "optimize-css-assets-webpack-plugin": "^6.0.1",
    "react-hot-loader": "^4.13.0",
    "sass-loader": "^13.1.0",
    "style-loader": "^3.3.1",
    "terser-webpack-plugin": "^5.3.6",
    "ts-loader": "^9.4.1",
    "webpack": "^5.74.0",
    "webpack-bundle-analyzer": "^4.6.1",
    "webpack-cli": "^4.10.0",
    "webpack-dev-server": "^4.11.1"
  }
  "sideEffects": [
    "*.css",
    "*.scss"
  ]
}

And here is a snippet from my webpack.config.json:

module.exports = {
  mode: 'development',
  entry: './src/index.tsx',
  output: {
    publicPath: '/',
    path: outPath,
    filename: 'bundle.js',
    globalObject: 'this'
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        exclude: [
          /(node_modules)/,
          /\.test.tsx?$/,
          /\.spec.tsx?$/
        ],
        use: [
          {loader: 'react-hot-loader/webpack'},
          {
            loader: 'ts-loader',
            options: {
              transpileOnly: true,
              allowTsInNodeModules: false,
              onlyCompileBundledFiles: true
            }
          }
        ]
      },
      {
        test: /\.(css|scss)$/,
        use: [
          {loader: 'style-loader'},
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              modules: {
                localIdentName: '[name]__[local]___[hash:base64:5]',
              },
            },
          },
          {
            loader: 'sass-loader',
            options: {
              sourceMap: true,
            },
          }
        ]
      }
    ]
  }
};

This is how I am importing styles in my modules:

const styles = require('./index.scss')

<div className={styles['some-class']}>

Everything was working fine with the previous webpack version, but after the upgrade, the styling is no longer being applied. Any assistance would be greatly appreciated.

Answer №1

When utilizing require instead of import, remember to include default:

const themes = require('./main.css').default;

Answer №2

I initially thought that the solution suggested above would resolve my problem, but interestingly enough, I realized I was not utilizing the require function.

Upon further investigation, I discovered that the project I was working on was employing

gajus/babel-plugin-react-css-modules
, which was facing an ongoing issue since April 2021. This issue highlighted a discrepancy in the generated hashes between the plugin and the css-loader 5.2.0. A helpful comment in the discussion led me to another comment recommending the use of a forked version due to the original plugin being inactive, along with a reference to a related StackOverflow post explaining the issue.

[..snip..]and this is why, following years of neglect by its creators, it encountered compatibility issues with the latest css-loader (due to changes in the class name generation logic of css-loader).

This StackOverflow post also pointed me towards an updated and maintained fork:

After implementing the necessary changes to switch to the new forked plugin, the CSS module sources were successfully integrated into my Webpack v5 build!

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

Design for implementing "new" functionality in JavaScript

I recently delved into the world of JavaScript Patterns through Stoyan Stefanov's book. One pattern that caught my attention involves enforcing the use of the new operator for constructor functions, demonstrated with the following code snippet: funct ...

customize Form Modal Bootstrap with AJAX Chained Dropdown for pre-selected options

I am facing an issue with a chained dropdown on a bootstrap modal, Here is the code snippet: function changeDetail(id) { var id = id; $('#edit').prop('hidden', true); $('#modal_form').prop('hidden', fa ...

How to import an HTML file using TypeScript

I need to load an html file located in the same directory as the typescript file and return it from the function. public ...(... ) : angular.IHttpPromise<string> { ... return $http({ method: 'GET', url: &apos ...

Retrieve SQL data and store it in a JavaScript variable

Need assistance with fetching data from SQL and storing it in a JavaScript variable. I have already connected PHPMyAdmin to my website. I am attempting to retrieve two variables (date) from my SQL table. JAVASCRIPT: var countdown_48 = new Date; countdow ...

Utilizing jQuery AJAX to transfer files from the client side in .NET platform

I need to upload files from the client side using a jQuery Ajax function to a location on a different server, rather than sending them to my application's web server. This is to prevent unauthorized or virus-infected uploads to the application web ser ...

oidc-client.js throws an error stating that no authority was provided

As someone new to SSO, I have recently been immersed in a project that utilizes OIDC. My focus has been on using oidc-client to address the issues at hand. Below are my settings (with some details redacted for privacy). var mgr = new Oidc.UserManager({ ...

Waiting for Promise Js to be fulfilled

I've been exploring the use of Bluebird for handling promises in Node.Js. I have encountered a situation where I need a function to return only when a promise is fulfilled. The desired behavior can be illustrated by the following code snippet: functi ...

the ajax success function is malfunctioning

I'm encountering an issue with my ajax function. I am trying to change the CSS for certain HTML elements on 'success', using the following code: success:function(d){ $('#name').css('weight','normal'); ...

Error: The array's property is not defined

I am currently working on a visualization tool for sorting algorithms, but I keep encountering an error that says "Cannot read properties of undefined (reading 'map')" in line let bars = this.state.array.map((value, index) =>. You can find my ...

Center the panel on the page and decrease its width using Bootstrap

I recently incorporated a Bootstrap panel above a search results table - my first experience working with Panels. This panel contains a form with a select menu, allowing users to filter the list of search results based on their selections. Currently, the ...

The concept of shallow routing in Next.js

I have a complex form with multiple steps and I want the path to change based on the current step of the form. After some research, I came across shallow routing as a potential solution for this issue. To implement this, I added a Router and an increase fu ...

Vue paginated select with dynamic data loading

My API has a endpoint that provides a list of countries. The endpoint accepts the following query parameters: searchQuery // optional search string startFrom // index to start from count // number of options to return For example, a request with searchQu ...

Unable to retrieve data. Issue: Unable to send headers after they have already been sent to the client

Experiencing an error while attempting to retrieve posts from a specific user. The code for fetching the data appears to be correct, so it's unclear where the error is originating from. Error from server side https://i.stack.imgur.com/ep1Xh.png Error ...

Handle all link clicks on the webpage

My challenge is that some users are required to utilize a virtual desktop in order to access specific information on my website. However, within the virtual environment, there are links leading to external content that do not function properly. I am seekin ...

Some variables are not being properly tracked by Google Analytics

Within the document.ready() function of the primary GSP layout in my application, I have included the following code: var pageTitle = document.getElementsByTagName('title')[0].innerHTML; if('index' == 'list') { pageTitle ...

Using ng-repeat to iterate over forms in AngularJS

I have implemented dynamic forms using the ng-repeat directive where form fields are generated based on the userid value. The requirement is that the add user button should be enabled only when all form fields are filled. However, currently the button rema ...

Implementing optimal techniques to create a JavaScript file for data retrieval in a Node.js application

I've developed a file specifically for data access purposes, where I'm keeping all my functions: const sql = require('mssql'); async function getUsers(config) { try { let pool = await sql.connect(conf ...

React - dynamically injecting external logic during execution

My goal is to modularize my React application by loading additional logic (such as containers/components) dynamically from an external .js file during runtime. For instance, I want to be able to introduce a new tab with completely different functionality o ...

Generate a customizable URL for my search bar

I have developed a single HTML page with full AJAX functionality, displaying all content including form submits, main page, form results, and more through various DOM manipulations. The issue I am currently encountering is related to a search box where use ...

Storing the selected value from a dropdown box in PHP

Can anyone help me with echoing the $row['price'] based on the user's GPU selection? Your input is greatly appreciated! #adding more content to meet word count requirements. <div id="content"> <table border="1" style="width: ...