Why is Ant design less styles not applied in nextjs app with Webpack5?

Viewed 2625

I am building a sample Nextjs app with webpack5 and for UI I am using Antd framework. I do not see the styles applied at all. When I go in the dev tools I do see ant classes applied to buttons but they are not styled. Here are my files:

globals.less:

@import 'antd/dist/antd.less';

_app.js:

import "../styles/globals.less";

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default MyApp

next.config.js: (for providing loaders and to use webpack5)

module.exports = {
  future: {
    webpack5: true,
  },
  webpack: (config, options) => {
    config.module.rules.push({
      test: /\.less$/,
      use: [
        {
          loader: "css-loader", // translates CSS into CommonJS
        },
        {
          loader: "less-loader", // compiles Less to CSS
          options: {
            lessOptions: {
              // If you are using less-loader@5 please spread the lessOptions to options directly
              modifyVars: {
                "primary-color": "#1DA57A",
                "link-color": "#1DA57A",
                "border-radius-base": "2px",
              },
              javascriptEnabled: true,
              sourceMap: true,
            },
          },
        },
      ],
    });

    return config;
  },
};

index.js:

import { Button } from 'antd'
import Head from 'next/head'

export default function Home() {
  return (
    <div>
      <Head>
        <title>Create Next App</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main >
        <h1 >
          Welcome to Nextjs
        </h1>
        <div>
          <Button type="primary">Primary Test</Button>
        </div>
      </main>
    </div>
  );
}

package.json:

{
  "name": "hello",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "@zeit/next-less": "^1.0.1",
    "antd": "^4.15.2",
    "babel-plugin-import": "^1.13.3",
    "css-loader": "^5.2.4",
    "less": "^4.1.1",
    "less-loader": "^8.1.1",
    "next": "10.1.3",
    "react": "17.0.2",
    "react-dom": "17.0.2"
  },
  "devDependencies": {}
}

When I look at the page through dev tools I don't even see the script tag.

Edit: for anyone saying use ~ in the path to less file please note that starting ver 8.0.0 it's been depracated. Here is the link to changelog: https://github.com/webpack-contrib/less-loader/blob/master/CHANGELOG.md

1 Answers

Prior to less-loader v8.0.0, you'll need to add a ~ to your antd.less import to tell the webpack loader to resolve the import from the node_modules directory.

@import '~antd/dist/antd.less';
Related