Search code examples
reactjstypescriptantdvite

How to change antd theme in Vite config?


It is a project composed of Vite & React & antd.

I want to handle antd theme dynamically in vite.config.ts.

I would appreciate it if you could tell me how to modify less.modifyVars value in React component.

This is the current screen.

light state / dark state

In dark mode, the style of the select component does not work properly.

import { getThemeVariables } from 'antd/dist/theme'

...

css: {
  modules: {
    localsConvention: 'camelCaseOnly'
  },
  preprocessorOptions: {
    less: {
      javascriptEnabled: true,
        modifyVars: {
          ...getThemeVariables({
            dark: true // dynamic
          })
        }
      }
    }
  }
}

Solution

  • It's been a while, but this is works for me now:

    You need to make sure you import less on demand. I use plugin vite-plugin-imp to achieve. And then getThemeVariables should be work well.

    import vitePluginImp from 'vite-plugin-imp';
    import { getThemeVariables } from 'antd/dist/theme';
    
    export default defineConfig({
      plugins: [
        // ...
        vitePluginImp({
          libList: [
            {
              libName: 'antd',
              style: (name) => `antd/es/${name}/style`,
            },
          ],
        }),
      ],
      resolve: {
        alias: [
          // { find: '@', replacement: path.resolve(__dirname, 'src') },
          // fix less import by: @import ~
          // https://github.com/vitejs/vite/issues/2185#issuecomment-784637827
          { find: /^~/, replacement: '' },
        ],
      },
      css: {
        preprocessorOptions: {
          less: {
            // modifyVars: { 'primary-color': '#13c2c2' },
            modifyVars: getThemeVariables({
              dark: true,
              // compact: true,
            }),
            javascriptEnabled: true,
          },
        },
      },
    });
    

    Moreover: you can get more inspiration from here: vite-react/vite.config.ts