您好,我想在我的简单Webpack项目中使用CSS模块。问题在于,编译后,webpack不会将样式类附加到我的HTML元素。
我可以在console.log(styles)
中看到带有编码样式的数组。但课程未添加到我的div中。
有人可以帮我这个忙吗?
**package.json**
"devDependencies": {
"@babel/core": "^7.6.4",
"@babel/preset-env": "^7.6.3",
"babel-loader": "^8.0.6",
"css-loader": "^3.2.0",
"path": "^0.12.7",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.9"
}
**webpack.config.js**
const path = require('path');
module.exports = {
// Path to your entry point. From this file Webpack will begin his work
entry: './src/js/app.js',
output: {
path: path.resolve(__dirname, 'public/assets'),
filename: '[name].bundle.js'
},
mode: 'development',
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
plugins: ['@babel/plugin-proposal-object-rest-spread']
}
}
},
{
test: /\.css$/i,
loader: 'css-loader',
options: {
modules: true,
},
},
]
}
};
**src/js/app.js**
import styles from "./css.module.css";
let el = document.getElementById('main');
el.innerHTML= '<div class="'+styles.red+'">RED OR NOT RED! This is the problem!</div>';
**src/js/css.module.css**
.red{ color: red; }
**public/index.html**
<div id="main"></div>
<script src="assets/main.bundle.js"></script>
您需要使用style-loader
将CSS注入dom。
style-loader