Chad.K
Chad.K

Reputation: 75

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
          })
        }
      }
    }
  }
}

Upvotes: 7

Views: 11686

Answers (2)

Yauhen
Yauhen

Reputation: 469

  1. You need to import 'antd/dist/antd.less' instead of 'antd/dist/antd.css'
  2. Install dependency for less npm add -D less. Vite will automatically catch it.
  3. Use the following config:
   css: {
     preprocessorOptions:{ 
       less: {
         modifyVars: {
           'primary-color': '#1DA57A',
           'heading-color': '#f00',
         },
         javascriptEnabled: true,
       },
     },
   },

Upvotes: 8

Yuns
Yuns

Reputation: 3010

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

Upvotes: 5

Related Questions