我想使用CSS模块,但是在webpack中配置CSS模块不生效,我想知道是不是我操作那里有错误
我曾尝试询问ChatGPT如何通过webpack使用CSS模块进行配置,但是其提供的CSS模块在运行时并没有生效
文件目录结构
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"
}
}
这是运行 npm start 后控制台错误消息的屏幕截图 在此输入图片描述
您应该引用相对于其自身位置的 JavaScript 捆绑文件。
在你的index.html中你说的是
<script src="dist/bundle.js"></script>
在你的 webpack.config 中你说
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
由于索引的路径位于目录“dist”中,您基本上是在告诉程序源位于MyProject/dist/dist
将您的index.html源更改为:
<script src="bundle.js"></script>
您还可以添加日志以在控制台中查看样式是否在您的index.js中正确加载
import styles from './styles.css';
console.log(styles); // This should log an object with your class names if correctly configured