如何使用 nextjs 12 设置 antd less 支持

how to setup antd less support with nextjs 12

我正在尝试使用 ant design antd 设置 nextjs 12,在 next.config.js 中,当我尝试使用 AntdLess 进行设置时,它给出了类型错误

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

尽管根据 next-plugin-antd-less 文档,所有 props 都是可选的

next.config.js 文件:

// @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-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]',
    },
  },
...
})

在文件顶部导入您的自定义 less 文件 _app.jsx

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

在您的自定义 less 文件中导入默认的 Antd less 文件:(在我的例子中 public/styles/custom.less

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

补充说明: 如果您有 Antd 的旧实现,您应该删除 .babelrc

中的集成
[
      "import",
      {
        "libraryName": "antd",
        "libraryDirectory": "lib",
        "style": true
      }
    ],

如果您有 Antd 的旧实现,您应该 删除 next.config.js

中 webpack 区域中的集成
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',
      });
    }