Vue less全局變量預處理加載


我們在vue中引入less:

 npm install less less-loader --save

配置less:

編輯 webpack.base.conf.js文件,修改module>rules添加:

 { 
        test: /\.less$/,
        loader: "style-loader!css-loader!less-loader",
    
      },

直接使用:

<template>
    <div class="container">Test1</div>
</template>
<style lang="less">
@color:#000;
@width: 100px;
@height: 100px;
@bg:#ccc;
.comm-font{
    color:@color;
    font-size:20px;
}
.container{
    width: @width;
    height: @height;
    background: @bg;
    .comm-font
}
</style>

這樣less已經可以使用了,可是對於一個工程來說,我們希望全局使用這些變量,公共樣式等

新建文件:src/assets/common/common.less存放公共變量樣式

@color:#000;
@width: 100px;
@height: 100px;
@bg:#ccc;
.common-container{
    background: @bg;
}

安裝資源預處理器Style Resources Loader

npm i style-resources-loader -D

修改build/utils.js文件中方法generateLoaders

  // generate loader string to be used with extract text plugin
  function generateLoaders (loader, loaderOptions) {
    const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader]

    if (loader) {
      loaders.push({
        loader: loader + '-loader',
        options: Object.assign({}, loaderOptions, {
          sourceMap: options.sourceMap
        })
      })
    }

    if(loader == 'less'){
      loaders.push({
          loader: 'style-resources-loader',
          options: {
              patterns: path.resolve(__dirname, '../src/assets/common/common.less')
          }
      })
    }


    // Extract CSS when that option is specified
    // (which is the case during production build)
    if (options.extract) {
      return ExtractTextPlugin.extract({
        use: loaders,
        fallback: 'vue-style-loader'
      })
    } else {
      return ['vue-style-loader'].concat(loaders)
    }
  }

現在就可以在全局使用了,我們看看效果:

<template>
    <div class="container">Test1</div>
</template>
<style lang="less">
.comm-font{
    color:@color;
    font-size:20px;
}
.container{
    width: @width;
    height: @height;
    background: @bg;
    .comm-font
}
</style>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM