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
import styles from './styles.css';
document.getElementById('app').innerHTML = `
<div class="${styles.container}">
<h1 class="${styles.title}">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="dist/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
slivername is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.