css-loader modules require is giving default property inside styles object in webpack 5

18 Views Asked by At

Webpack.config.js

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const path = require('path');
module.exports = {
    mode: 'development',
    module: {
        rules: [{
            test: /\.s?css$/i,
            use: [MiniCssExtractPlugin.loader, {
                loader: "css-loader",
                options: {
                    importLoaders: 2,
                    modules: {
                        localIdentName: "[name]-[local]-[hash:base64:5]",
                    }

                },
            }, "sass-loader", {
                loader: 'postcss-loader',
                options: {
                    postcssOptions: {
                        config: path.resolve(__dirname, 'config/postcss.config.js')
                    }
                }
            }]
        }
        ]
    },
    plugins: [new MiniCssExtractPlugin()],
    devtool: 'source-map'
}

styles.scss

:root {
  --mainBg: salmon;
}

$light-text: moccasin;
body {
  background-color: var(--mainBg);
  color: $light-text;
}

.container {
  padding: 1rem;
  display: flex;
  background: linear-gradient(to top, black, white);
  h1 {
    font-size: 68px;
    text-align: center;
  }
}


main.js

import './style.scss';
import './woof.css';
const styles = require('./styles.scss');
console.log({ styles });
document.querySelector('h2').innerHTML = `<div classs="${styles.container}">hello fron container</div>`

For the above code in the console, I am getting the below given object

{
    "styles": {
        "default": {
            "container": "styles-container-XyxFI",
            "error": "styles-error-x9eaL"
        }
    }
}

Expected:

{
    "styles": {
            "container": "styles-container-XyxFI",
            "error": "styles-error-x9eaL"
    }
}

I am getting the expected output object if use an import statement. like this:

// import styles from './styles.scss';

but I can change the require to import because it is used in multiple places. is there any way to get the expected output without using import?

0

There are 0 best solutions below