我已经使用 webpack 加载了 CSS,并且可以设置 HTML 标签的样式,但不能使用类或 ID 设置样式。我想知道这是否与我的依赖顺序有关,或者我加载 CSS 的方式有关。
例如,这个有效:
span {
background-color: teal;
display: inline-block;
width: 20px;
height: 75px; /* We'll override this later */
}
但这不是:
.bar {
background-color: teal;
display: inline-block;
width: 20px;
height: 75px; /* We'll override this later */
}
这是我的 webpack.config.js 文件。
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html',
inject: 'body'
})
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve('dist'),
filename: 'index_bundle.js'
},
module: {
rules: [
{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
{
test: /\.css$/,
use: [
{ loader: 'style-loader'},
{
loader: 'css-loader',
options: {
modules: true
}
},
]
},
]
},
plugins: [HtmlWebpackPluginConfig]
}
这是我的 HTML 文件。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>D3</title>
</head>
<body>
<span class="bar"></span>
</body>
</html>
这是我的 index.js 文件。
import * as d3 from 'd3';
import styles from './style.css';
var dataset = [5, 10, 15, 20, 25];
最佳答案
它不起作用,因为您启用了 css modules在你的 webpack 配置中。在构建过程中,这些类将被生成的类(本地类)替换。要为您的配置禁用 css 模块,只需将属性更改为 modules: false
,如下所示:
use: [
{ loader: 'style-loader'},
{
loader: 'css-loader',
options: {
modules: false
}
},
]
或者,如果您想保留 css 模块并解决问题,您必须:
1) 在您的 HTML 中使用生成的类
2) 将您的选择器更改为全局选择器:
:global{
.bar {
background-color: teal;
display: inline-block;
width: 20px;
height: 75px; /* We'll override this later */
}
}
关于javascript - 使用 webpack 加载 CSS 时,我可以为标签编写 CSS,但不能为类或 ID 编写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42402151/