antd 在webpack.config配置主题色

虽然官方提供了craco-less 来 覆盖less-loader 提供的 less 变量,但自己也想试着修复config来配置一下

首先需要运行 yarn eject 来暴露webpack的配置
其次需要安装less-loader(注意这个需要在3以下) 和 babel-plugin-import

yarn add less@^2.7.3
yarn add babel-plugin-import

然后打开webpack.config.js

一、配置babel全局引入antd.css

在对应的 test: /\.(js|mjs|jsx|ts|tsx)$/, 方法的plugins中增加

      ['import',{
        libraryName:'antd',
        style:true
      }],

修改后如下

    // Process application JS with Babel.
    // The preset includes JSX, Flow, TypeScript, and some ESnext features.
    {
      test: /\.(js|mjs|jsx|ts|tsx)$/,
      include: paths.appSrc,
      loader: require.resolve('babel-loader'),
      options: {
        customize: require.resolve(
          'babel-preset-react-app/webpack-overrides'
        ),
        presets: [
          [
            require.resolve('babel-preset-react-app'),
            {
              runtime: hasJsxRuntime ? 'automatic' : 'classic',
            },
          ],
        ],
        
        plugins: [
          [
            require.resolve('babel-plugin-named-asset-import'),
            {
              loaderMap: {
                svg: {
                  ReactComponent:
                    '@svgr/webpack?-svgo,+titleProp,+ref![path]',
                },
              },
            },
          ],
          ['import',{
            libraryName:'antd',
            style:true
          }],
          isEnvDevelopment &&
            shouldUseReactRefresh &&
            require.resolve('react-refresh/babel'),
        ].filter(Boolean),
        // This is a feature of `babel-loader` for webpack (not Babel itself).
        // It enables caching results in ./node_modules/.cache/babel-loader/
        // directory for faster rebuilds.
        cacheDirectory: true,
        // See #6846 for context on why cacheCompression is disabled
        cacheCompression: false,
        compact: isEnvProduction,
      },
    },

二、增加less-loader

// style files regexes
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;

代码中增加less 正则变量

// style files regexes
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;

然后拷贝一份如下配置css-loader代码

    // "postcss" loader applies autoprefixer to our CSS.
    // "css" loader resolves paths in CSS and adds assets as dependencies.
    // "style" loader turns CSS into JS modules that inject