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 using CSS Modules feature with Ant Design

See original GitHub issue

Bug report

Describe the bug

When I setup my Next.js with support Ant Design. I can’t use CSS Modules feature of Next.js

To Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Here is my test project: https://github.com/thobn24h/nextjs-with-ant
  2. Run yarn dev to build project
  3. Go to link: http://localhost:3000 to view web
  4. Get error:
./components/Header.module.css 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> .appc {
|   color: #fff;
|   background: #16191e;

Configurations:

  1. next.config.js
/* eslint-disable */
const withLess = require('@zeit/next-less');
const withSass = require('@zeit/next-sass');
const lessToJS = require('less-vars-to-js');
const fs = require('fs');
const path = require('path');

// Where your antd-custom.less file lives
const themeVariables = lessToJS(
  fs.readFileSync(path.resolve(__dirname, './css/antd.less'), 'utf8')
);

module.exports = withSass({
  cssModules: true,
  ...withLess({
    lessLoaderOptions: {
      javascriptEnabled: true,
      modifyVars: themeVariables, // make your antd custom effective
      importLoaders: 0
    },
    cssLoaderOptions: {
      importLoaders: 3,
      localIdentName: '[local]___[hash:base64:5]'
    },
    webpack: (config, { isServer }) => {
      //Make Ant styles work with less
      if (isServer) {
        const antStyles = /antd\/.*?\/style.*?/;
        const origExternals = [...config.externals];
        config.externals = [
          (context, request, callback) => {
            if (request.match(antStyles)) return callback();
            if (typeof origExternals[0] === 'function') {
              origExternals[0](context, request, callback);
            } else {
              callback();
            }
          },
          ...(typeof origExternals[0] === 'function' ? [] : origExternals)
        ];

        config.module.rules.unshift({
          test: antStyles,
          use: 'null-loader'
        });
      }
      return config;
    }
  })
});
  1. test file: pages/index.tsx
import headerStyled from '../components/Header.module.css'

export default () => {
  return (
    <>
      <div className={headerStyled.appc}>
        Hello World
      </div>
    </>
  )
}

Expected behavior

Can view website normally with using CSS Modules feature.

Screenshots

css_modules_error

System information

  • OS: macOS 10.15.5
  • Browser (if applies) safari
  • Version of Next.js: next@^9.4.4
  • Version of Node.js: v10.16.0

Additional context

Add any other context about the problem here.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:1
  • Comments:15 (6 by maintainers)

github_iconTop GitHub Comments

7reactions
jamesmosiercommented, Jul 6, 2020

Anytime you alter the webpack config you run the risk of something within Next breaking unintentionally. So I would certainly exercise caution with this. But glad it worked for you!

For now there is no official way to do this.

6reactions
thobn24hcommented, Jul 6, 2020

After ask on some channels ( Stack Overflow, Medium, GitLab, … ), Sumit Sarkar (@sumitsarkar01) was helped me config the next.config.js ,
And now, It work correctly!
@jamesmosier, could you review it for me ? Is the any way simple or official about this case ?

const withLess = require('@zeit/next-less')
const lessToJS = require('less-vars-to-js')
const withPlugins = require('next-compose-plugins')

const fs = require('fs')
const path = require('path')

const dotenv = require('dotenv')

dotenv.config()

// Where your antd-custom.less file lives
const themeVariables = lessToJS(
  fs.readFileSync(path.resolve(__dirname, './css/antd.less'), 'utf8')
)

const plugins = [
  [withLess({
    lessLoaderOptions: {
      javascriptEnabled: true,
      modifyVars: themeVariables, // make your antd custom effective
    },
    webpack: (config, { isServer }) => {
      if (isServer) {
        const antStyles = /antd\/.*?\/style.*?/
        const origExternals = [...config.externals]
        config.externals = [
          (context, request, callback) => {
            if (request.match(antStyles)) return callback()
            if (typeof origExternals[0] === 'function') {
              origExternals[0](context, request, callback)
            } else {
              callback()
            }
          },
          ...(typeof origExternals[0] === 'function' ? [] : origExternals),
        ]

        config.module.rules.unshift({
          test: antStyles,
          use: 'null-loader',
        })
      }

      const builtInLoader = config.module.rules.find((rule) => {
        if (rule.oneOf) {
          return (
            rule.oneOf.find((deepRule) => {
              return deepRule.test && deepRule.test.toString().includes('/a^/');

            }) !== undefined
          );
        }
        return false;
      });

      if (typeof builtInLoader !== 'undefined') {
        config.module.rules.push({
          oneOf: [
            ...builtInLoader.oneOf.filter((rule) => {
              return (rule.test && rule.test.toString().includes('/a^/')) !== true;
            }),
          ],
        });
      }

      config.resolve.alias['@'] = path.resolve(__dirname);
      return config;
    }
  })]
]

const nextConfig = {
  env: {
  }
}

module.exports = withPlugins(plugins, nextConfig)

@maysam, I was updated this config to my test project, you can check it out https://github.com/thobn24h/nextjs-with-ant

Read more comments on GitHub >

github_iconTop Results From Across the Web

Can not use CSS modules in Nextjs, Ant Design?
From my tries, this solution requires @zeit/next-less , @zeit/next-css , less , less-loader as dependencies ‍♂️.
Read more >
Style - Ant Design
CSS Modules Detailed and Practice in React. Style file category#. In a project, style files can be divided into different categories depending on...
Read more >
Getting Started - Ant Design
Ant Design React is dedicated to providing a good development experience for programmers. Before starting, it is recommended to learn React and ES2015...
Read more >
CSS Modules - Ant Design Pro
CSS Modules. CSS Modules. Two issues stand out in the style development process. global contamination -- selectors in CSS files are globally ...
Read more >
Getting Started | NG-ZORRO - Ant Design
Angular Getting Started Component, Ant Design of Angular is dedicated to providing ... that you want to use into the app.module.ts file and...
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