如何在Vite配置中更改antd主题?

Cha*_*d.K 6 typescript reactjs antd vite

是一个由 Vite & React & antd 组成的项目。

我想在 vite.config.ts 中动态处理 antd 主题。

如果您能告诉我如何修改 React 组件中的 less.modifyVars 值,我将不胜感激。

这是当前屏幕。

亮态/ 暗态

深色模式下,select组件的样式无法正常使用。

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

...

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

Yau*_*hen 7

  1. 您需要导入 'antd/dist/antd.less' 而不是 'antd/dist/antd.css'
  2. 安装依赖项较少npm add -D less。Vite会自动捕捉。
  3. 使用以下配置:
   css: {
     preprocessorOptions:{ 
       less: {
         modifyVars: {
           'primary-color': '#1DA57A',
           'heading-color': '#f00',
         },
         javascriptEnabled: true,
       },
     },
   },
Run Code Online (Sandbox Code Playgroud)


Yun*_*uns 4

已经有一段时间了,但这现在对我有用:

您需要确保减少按需进口。我是用插件vite-plugin-imp来实现的。然后getThemeVariables应该可以很好地工作。

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

此外:您可以从这里获得更多灵感:vite-react/vite.config.ts