首页 > 解决方案 > how to setup antd less support with nextjs 12

问题描述

im trying to setup nextjs 12 with ant design antd and in next.config.js when i try to setup withAntdLess it gives type error

Type '{}' is missing the following properties from type '{ esModule: boolean; sourceMap: boolean; modules: { mode: string; }; }': esModule, sourceMap, modules

although all props are optional according to next-plugin-antd-less docs

next.config.js file:

// @ts-check
// next.config.js
const withAntdLess = require('next-plugin-antd-less');
/**
 * @type {import('next').NextConfig}
 **/

 
module.exports =withAntdLess({
  cssLoaderOptions: {},

  // Other Config Here...

  webpack(config) {
    return config;
  },

  
  reactStrictMode: true,
});

标签: next.jslessantd

解决方案


I solved it using next-with-less https://github.com/elado/next-with-less

next.config.js

const withLess = require('next-with-less');
const lessToJS = require('less-vars-to-js');

const themeVariables = lessToJS(
  fs.readFileSync(
    path.resolve(__dirname, './public/styles/custom.less'),
    'utf8'
  )
);

module.exports = withLess({
...
lessLoaderOptions: {
    lessOptions: {
      javascriptEnabled: true,
      modifyVars: themeVariables, // make your antd custom effective
      localIdentName: '[path]___[local]___[hash:base64:5]',
    },
  },
...
})

Import your custom less file on top off the file _app.jsx

import 'public/styles/custom.less';
...

Import the default Antd less file on your custom less file: (in my case public/styles/custom.less)

@import "~antd/dist/antd.less";
....

Extra notes: If you have an old implementation of Antd, you should remove the integration in your .babelrc

[
      "import",
      {
        "libraryName": "antd",
        "libraryDirectory": "lib",
        "style": true
      }
    ],

If you have an old implementation of Antd, you should remove the integration in your webpack zone in your next.config.js

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',
      });
    }

推荐阅读