question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Can't get CSS modules and antd styles to work at the same time

See original GitHub issue

Hi @ndbroadbent , @patricklafrance !

I am trying to get CSS Modules to work as well as antd.

So far, I either have antd’s styles working, or CSS Modules, but I can’t get both to work at the same time.

To get antd’s styling to work, I have to comment out cssLoaderOptions... (see in my code below), but then CSS Modules don’t work anymore.

If I leave cssLoaderOptions, CSS Modules work, but antd seems to lose some styling. For example, I can still see some animation when clicking on a button, but the color styling and shaping is gone.

Here’s a link to my repo.

const CracoAntDesignPlugin = require("craco-antd");
const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");
const WebpackBar = require("webpackbar");

// Don't open the browser during development
process.env.BROWSER = "none";

module.exports = {
  webpack: {
    plugins: [
      new WebpackBar({ profile: true }),
      ...(process.env.NODE_ENV === "development"
        ? [new BundleAnalyzerPlugin({ openAnalyzer: false })]
        : []),
    ],
  },
  plugins: [
    {
      plugin: CracoAntDesignPlugin,

      options: {
        modifyLessRule: function(lessRule, _context) {       
          lessRule.test = /\.less$/;
          lessRule.exclude = undefined;

          // console.log('lessRule', lessRule)
          // console.log('JSON', JSON.stringify(lessRule.use))        

          return lessRule;
        },       

        // CSS Modules. This makes the styling of antd to stop working. If I comment out, antd's styling works.
        cssLoaderOptions: {
          modules: true,
          localIdentName: `${
            process.env.NODE_ENV === "production"
              ? "[local]_[hash:base64:5]"
              : "[path][name]__[local]-"
          }-[hash:base64:8]`,
        },
      },
    },
  ],
};

I’m using those versions:

"@craco/craco": "5.0.2",
"antd": "^3.16.6",
"craco-antd": "1.10.0",
"react-scripts": "3.0.0",
"typescript": "^3.4.5"

This is the bundle analyzer when antd works (when I comment out cssLoaderOptions), 2.44Mb:

image

This is when CSS Module work (2.36Mb)

image

Issue Analytics

  • State:open
  • Created 4 years ago
  • Reactions:2
  • Comments:13 (2 by maintainers)

github_iconTop GitHub Comments

21reactions
mdluocommented, Jun 3, 2020

@gregoryforel Here’s my solution:

const path = require('path');

const WebpackBar = require('webpackbar');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const CracoAntDesignPlugin = require('craco-antd');
const CracoLessPlugin = require('craco-less');

module.exports = {
  webpack: {
    plugins: [
      new WebpackBar({ profile: true }),
      ...(process.env.NODE_ENV === 'development'
        ? [new BundleAnalyzerPlugin({ openAnalyzer: false })]
        : []),
    ],
  },
  plugins: [
    {
      plugin: CracoAntDesignPlugin,
      options: {
        customizeTheme: getThemeVariables({
          dark: true,
        }),
        customizeThemeLessPath: path.join(__dirname, 'src/styles/theme.less'),
      },
    },
    {
      plugin: CracoLessPlugin,
      options: {
        cssLoaderOptions: {
          modules: { localIdentName: '[local]_[hash:base64:5]' },
        },
        modifyLessRule: function(lessRule, _context) {
          lessRule.test = /\.(module)\.(less)$/;
          lessRule.exclude = path.join(__dirname, 'node_modules');
          return lessRule;
        },
      },
    },
  ],
};

The first CracoAntDesignPlugin is to load the antd components and the customize theme variables file. And CSS modules option is turned off (by default), otherwise the antd component’s styles won’t be load properly.

And the second CracoLessPlugin is to load application-level .module.less files, with CSS modules enabled.

Updated the cssLoaderOptions, thanks to @pmosconi 's comment

6reactions
rnelcommented, Oct 1, 2019

@mdluo, another solution is to use getLocalIdent:

const path = require('path');
const CracoAntDesignPlugin = require("craco-antd");
const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent'); // included in Create React App

module.exports = {
  plugins: [
    {
      plugin: CracoAntDesignPlugin,
      options: {
        cssLoaderOptions: {
          modules: true,
          getLocalIdent: (context, localIdentName, localName, options) => {
            if (context.resourcePath.includes('node_modules')) {
              return localName;
            }
            return getCSSModuleLocalIdent(context, localIdentName, localName, options);
          }
        },
        customizeThemeLessPath: path.join(__dirname, 'src/styles/theme.less')
      }
    }
  ]
};

For third-party LESS files (i.e. those inside node_modules), you should return localName to avoid adding hash to css class names.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Can't get CSS modules and antd styles to work at the same time
I am trying to get CSS Modules to work as well as antd . So far, I either have antd 's styles working,...
Read more >
CSS Modules + Ant design in ReactJs does not work
config in Rule section it will work with Css modules and overriding less styles of antd components. { test: /\.less$/, include: [/src/], use: ......
Read more >
Component-level CSS-in-JS - Ant Design
According to the style structure we determined from v4 and previous versions, the style of each component will not change under the same...
Read more >
How to configure CSS and CSS modules in webpack
Before we configure CSS support in the webpack setup, let's first add a CSS file and use it. The first thing we are...
Read more >
FAQs - styled-components
At this time we do not recommend using @import within cGS due to some issues ... In general, always use the css helper...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found