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

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

less簡單介紹與使用

less官網(wǎng):http://lesscss.org

less中文網(wǎng):http://lesscss.cn

Less是一款比較流行的css預(yù)處理語言,支持變量、混合、函數(shù)、嵌套、循環(huán)等特點(diǎn)。

Less 的一個主要功能就是可以讓你像在其它高級語言中一樣聲明變量,這樣你就可以存儲你經(jīng)常使用的任何類型的值 : 顏色,尺寸,選擇器,字體名稱和 URL 等。less 的哲學(xué)是在可能的情況下重用CSS語法。

less的簡單使用

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

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

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

1、less相關(guān)插件依賴下載

其中用到了 lessless-loader、style-resources-loader、vue-cli-plugin-style-resources-loader
博主是通過圖形化界面添加的,其中less-loader版本過高,運(yùn)行報錯,找個另外一個替代@kkt/loader-less

期間報的錯:

Failed to resolve loader: style-resources-loader

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

也有提示less或less-loader等依賴沒找到之類的

在這里插入圖片描述
在這里插入圖片描述

命名行添加(網(wǎng)上看的沒試)

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設(shè)置
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配置,也可單獨(dú)頁面引用,不過不推薦
// @import "../../less/global.less";
.bg {
  background: @base-bgColor;
}
</style>

5、安裝完成,重啟服務(wù)運(yùn)行

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")]
    })
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容