Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Vant custom theme


May 07, 2021 Vant


Table of contents


Introduced

Vant offers a default set of themes, and CSS is named in BEM style for easy consumer overlay styles. If you want to completely replace the theme color or other styles, you can use the methods provided below.

Example project

We provide a sample project based on Vue Cli 3, with a warehouse address of Vant Demo, which contains the basic configuration of a custom theme that can be used as a reference.

The style variable

Vant uses Less to preprocess styles and has built-in style variables to customize the theme you want by replacing them.

Here are some basic style variables, all available color variables refer to the profile.

// Component Colors
@text-color: #323233;
@border-color: #ebedf0;
@active-color: #f2f3f5;
@background-color: #f7f8fa;
@background-color-light: #fafafa;

Custom methods

Step 1 Introduces a style source file

When customizing a theme, you need to introduce a Less-style file for the component that supports both on-demand and manual introduction.

On-demand introduction styles (recommended)

Configure on-demand ingest .js file in babel.config.js, note that babel6 does not support on-demand ingested styles, please introduce styles manually

module.exports = {
  plugins: [
    [
      'import',
      {
        libraryName: 'vant',
        libraryDirectory: 'es',
        // 指定样式路径
        style: name => `${name}/style/less`
      },
      'vant'
    ]
  ]
};

The style is introduced manually

// 引入全部样式
import 'vant/lib/index.less';

// 引入单个组件样式
import 'vant/lib/button/style/less';

Step two Modify the style variable

Variables can be modified using modifyVars provided by Less, and the following is the reference webpack configuration.

// webpack.config.js
module.exports = {
  rules: [
    {
      test: /\.less$/,
      use: [
        // ...其他 loader 配置
        {
          loader: 'less-loader',
          options: {
            modifyVars: {
              // 直接覆盖变量
              'text-color': '#111',
              'border-color': '#eee'
              // 或者可以通过 less 文件覆盖(文件路径为绝对路径)
              'hack': `true; @import "your-less-file-path.less";`
            }
          }
        }
      ]
    }
  ]
};


Example demonstration