Vue - vue-cli4.x配置less全局变量(vant和自定义)

demo 地址: https://github.com/iotjin/jh-vue-demo

less简单介绍与使用

less官网:http://lesscss.org

less中文网:http://lesscss.cn

Less是一款比较流行的css预处理语言,支持变量、混合、函数、嵌套、循环等特点。

Less 的一个主要功能就是可以让你像在其它高级语言中一样声明变量,这样你就可以存储你经常使用的任何类型的值 : 颜色,尺寸,选择器,字体名称和 URL 等。less 的哲学是在可能的情况下重用CSS语法。

less的简单使用

@width: 10px;
@height: @width + 10px;

#header {
      
      
  width: @width;
  height: @height;
}

vue-cli4.x配置less全局变量

1、less相关插件依赖下载

其中用到了 lessless-loaderstyle-resources-loadervue-cli-plugin-style-resources-loader
博主是通过图形化界面添加的,其中less-loader版本过高,运行报错,找个另外一个替代@kkt/loader-less

期间报的错:

Failed to resolve loader: style-resources-loader

Syntax Error: TypeError: this.getOptions is not a function

也有提示less或less-loader等依赖没找到之类的

在这里插入图片描述

在这里插入图片描述
命名行添加(网上看的没试)

npm install style-resources-loader vue-cli-plugin-style-resources-loader less-loader less -S

2、在vue.config.js文件里面配置

const path = require('path');
function resolve(dir) {
    
    
  return path.join(__dirname, dir);
}

// less设置
pluginOptions: {
    
    
  'style-resources-loader': {
    
    
    preProcessor: 'less',
    patterns: [
      resolve("src/less/global.less")
    ]
  }
}

3、global.less

其中添加了vant的配置和自定义的配置

@import "~vant/lib/index.less";

@nav-bar-height: 46px;
@nav-bar-background-color: red;
@nav-bar-title-font-size: 18;
@nav-bar-title-text-color: #fff;

@base-bgColor: yellow;

4、页面引用

<style lang="less">
//如果没有在vue.config.js配置,也可单独页面引用,不过不推荐
// @import "../../less/global.less";
.bg {
    
    
  background: @base-bgColor;
}
</style>

5、安装完成,重启服务运行

npm run serve

另一种vue.config.js配置方式

// vue.config.js文件中的配置
const path = require('path') 
module.exports = {
    
    
    chainWebpack: config => {
    
    
        const types = ['vue-modules', 'vue', 'normal-modules', 'normal']
        types.forEach(type =>     
        addStyleResource(config.module.rule('less').oneOf(type)))
    }
}
 
// add style resource
function addStyleResource(rule) {
    
    
  rule.use('style-resource')
    .loader('style-resources-loader')
    .options({
    
    
      patterns: [path.resolve(__dirname, "./src/less/global.less")]
    })
}

猜你喜欢

转载自blog.csdn.net/iotjin/article/details/117748441