Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The issue of using CSS modules in webpack 5

I want to use CSS modules, but configuring CSS modules in webpack does not take effect,I want to know if there was a mistake in my operation there

I have tried asking ChatGPT how to use CSS module to configure through webpack,But the CSS module provided by it does not take effect at runtime

file directory structure

my-project/
  |-dist/
      |-index.html
  |- src/
  |   |- index.js
  |   |- styles.css
  |- webpack.config.js
  |- package.json

webpack.config.js

const path = require('path');

module.exports = {
  entry: './src/index.js', 
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js' 
  },
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [
          'style-loader', 
          {
            loader: 'css-loader', 
            options: {
              modules: true
            }
          }
        ]
      }
    ]
  }
};

/src/styles.css

//styles.css
.container {
  width: 100%;
  max-width: 960px;
  margin: 0 auto;
}

.title {
  color: blue;
}

/src/index.js

// index.js
// index.js
import styles from "./styles.css";

console.log("styles", styles);
document.getElementById("app").innerHTML = `
  <div class="${styles.container}">
    <h1>Hello, CSS Modules!</h1>
  </div>
`;

/dist/index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CSS Modules Example</title>
</head>
<body>
  <div id="app"></div>
  <script src="bundle.js"></script>
</body>
</html>

package.json

{
  "name": "testbar",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack serve --config webpack.config.js --open"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "css-loader": "^7.1.1",
    "style-loader": "^4.0.0",
    "webpack": "^5.91.0",
    "webpack-cli": "^5.1.4",
    "webpack-dev-server": "^5.0.4"
  }
}

This is a screenshot of the console error message after running npm start enter image description here

enter image description here

like image 918
slivername Avatar asked Oct 18 '25 11:10

slivername


1 Answers

try to add this namedExport: false

 module: {
rules: [
  {
    test: /\.css$/i,
    use: [
      'style-loader', 
      {
        loader: 'css-loader', 
        options: {
          namedExport: false,
          modules: true
        }
      }
    ]
  }
]

}

like image 104
Артур Шахвердян Avatar answered Oct 20 '25 02:10

Артур Шахвердян