javascript - 使用 webpack 加载 CSS 时,我可以为标签编​​写 CSS,但不能为类或 ID 编写

标签 javascript html css d3.js webpack

我已经使用 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/

相关文章:

javascript - jQuery 或 JavaScript 中是否有等效的 ScrollBottom?

javascript - 在 Javascript 中引用 window 对象的目的是什么?

javascript - Closure Compiler 并不总是强制类型安全?

javascript - 使可切换内容占据剩余高度

html - 如何将 `display:none;` 应用于除 `<td class="cc">text</td>` 之外的所有内容?

javascript - 在 React 中滚动到可滚动 div 的底部

javascript - CSS - 在 Bootstrap 5 中使用 Typehead.js 时变得不确定

javascript - 在字符串javascript中插入换行符

javascript - 使用node.js访问服务器端的Json文件

javascript - jquery mouseenter 在尺寸大于父 div 的子 div 上