基于nuxt通过webpack配置ant-Design-vue的主题切换配置

1.首先在nuxt官网初始化好基于ant-Design-vue的项目,

nuxt官网链接 https://zh.nuxtjs.org/guide/installation

安装.png

选择ant-Design-vue UI框架

2.初始化完成,查找package.json是否安装了less与less-loader的包,

package.json.png

一般项目在初始化完成后,是没有自动安装less与less-loader的,需要我们手动去配置,
通过npm less less-loader --save-dev去安装

3.安装完成less与less-loader后,配置nuxt.config.js

找到nuxt.config.js这个文件夹,该文件在项目根目录
这是没有修改,nuxt初始化好的配置文件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
module.exports = {
  mode: 'universal',
  /*
  ** Headers of the page
  */
  head: {
    title: process.env.npm_package_name || '',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: process.env.npm_package_description || '' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },
  /*
  ** Customize the progress-bar color
  */
  loading: { color: '#fff' },
  /*
  ** Global CSS
  */
  css: [
    'ant-design-vue/dist/antd.css'
  ],
  /*
  ** Plugins to load before mounting the App
  */
  plugins: [
    '@/plugins/antd-ui'
  ],
  /*
  ** Nuxt.js modules
  */
  modules: [
  ],
  /*
  ** Build configuration
  */
  build: {
    /*
    ** You can extend webpack config here
    */
    extend(config, ctx) {
    },
  }
}

找到css属性,在这个地方就是去扩展webpack配置的东西,将引用是.css文件改为less文件

1
2
3
4
5
6
/*
  ** Global CSS
  */
  css: [
    'ant-design-vue/dist/antd.css'
  ],

然后找到注解为you can extend webpack config here的地方,这里就是进行webpack配置的地方了,我们需要将安装的less-loader进行配置,这里配置的方法有两种

第一种,在extend的方法中通过config这个属性去获取webpack的modul.rules属性进行扩展,

rules这个属性是一个数组,我们通过push方法来给rules添加less的相关配置,直接上代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
extend(config, ctx) {
      console.log(config)
      config.module.rules.push(
        {
          test:/.less/,
          loader: 'less-loader', // compiles Less to CSS
          options: {
            modifyVars: {
              'primary-color': '#1DA57A',
              'link-color': '#1DA57A',
              'border-radius-base': '2px',
            },
            javascriptEnabled: true,
          },
        }
      )
    },

配置好后,关闭服务器,重新启动,npm run dev就可以看到效果

第二种方法,直接在build这个属性下面去添加loaders这个属性去配置,话不多说直接上代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 build: {
    /*
    ** You can extend webpack config here
    */
     loaders: {
       less: {
         javascriptEnabled: true,
        modifyVars: {
           'primary-color': '#41b883',
          'layout-body-background': '#fff'
         }
       }
     }
  }
}

配置好后,关闭服务器,重新启动,npm run dev就可以看到效果

最后效果

效果一.png

效果二.png