Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When loading CSS with webpack, I can write CSS for tags, but not for classes or ids

I have loaded CSS using webpack and can style HTML tags, but cannot style using classes or ids. I'm wondering if it has to do with my order of dependencies, or the way I am loading the CSS.

For example, this works:

span {
    background-color: teal;
    display: inline-block; 
    width: 20px;
    height: 75px;   /* We'll override this later */
}

but this doesn't:

.bar {
    background-color: teal;
    display: inline-block; 
    width: 20px;
    height: 75px;   /* We'll override this later */
}

This is my webpack.config.js file.

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]
}

This is my HTML file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>D3</title>
</head>
<body>
    <span class="bar"></span>
</body>
</html>

This is my index.js file.

import * as d3 from 'd3';
import styles from './style.css';

var dataset = [5, 10, 15, 20, 25];
like image 474
maecapozzi Avatar asked Sep 05 '25 02:09

maecapozzi


1 Answers

It does not work because you have enabled css modules in your webpack configuration. During a build, the classes will be replaced with generated ones (local classes). In order to disable css modules for your configuration simply change the property to modules: false, as such:

use: [
  { loader: 'style-loader'},
  {
    loader: 'css-loader',
    options: {
      modules: false
    }
  },
]

Or, if you want to keep css modules on and fix the problem you must either:

1) use generated classes in your HTML

2) change your selectors to global as:

:global{
    .bar {
        background-color: teal;
        display: inline-block; 
        width: 20px;
        height: 75px;   /* We'll override this later */
    }
}
like image 67
Adam Wolski Avatar answered Sep 07 '25 23:09

Adam Wolski