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

Maj*_*aji 6 less next.js antd

我尝试使用 ant design antd 和 next.config.js 设置 nextjs 12,当我尝试使用 AntdLess 设置时,它会给出类型错误

类型“{}”缺少类型“{ esModule: boolean;”中的以下属性 源映射:布尔值;模块:{ 模式:字符串;}; }':esModule、sourceMap、模块

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

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,
});
Run Code Online (Sandbox Code Playgroud)

小智 9

我使用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]',
    },
  },
...
})
Run Code Online (Sandbox Code Playgroud)

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

import 'public/styles/custom.less';
...
Run Code Online (Sandbox Code Playgroud)

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

@import "~antd/dist/antd.less";
....
Run Code Online (Sandbox Code Playgroud)

额外注意事项:如果您有旧的 Antd 实现,您应该删除您的集成.babelrc

[
      "import",
      {
        "libraryName": "antd",
        "libraryDirectory": "lib",
        "style": true
      }
    ],
Run Code Online (Sandbox Code Playgroud)

如果您有旧的 Antd 实现,您应该在您的 webpack 区域中删除集成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',
      });
    }
Run Code Online (Sandbox Code Playgroud)