我們在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>