項目開發過程中我們可能會定義一些公共樣式、變量、mixin...,在任意單文件中可以隨時自由的引用這些公共樣式和變量,那么我們就可以使用style-resources-loader,這篇文章將介紹如何使用它。
一、預處理器安裝
根據不同預處理器(Sass/Less/Stylus),安裝響應的webpack loader:
// Sass
npm install -D sass-loader sass
// Less
npm install -D less-loader less
// Stylus
npm install -D stylus-loader stylus
二、安裝style-resources-loader
// 使用vue add安裝
vue add style-resources-loader
三、配置vue.config.js
在pluginOptions>style-resources-loader定義資源的模式。配置項:
名稱 | 類型 | 例如 |
---|---|---|
preProcessor | string | sass, scss, stylus, less中的一種 |
patterns | string, array | 資源路徑或者資源路徑數組 |
四、案例
// vue.config.js
const path = require('path')
module.exports = {
pluginOptions: {
'style-resources-loader': {
'preProcessor': 'scss', // 項目中使用scss
'patterns': [
path.resolve(__dirname, './src/styles/*.scss'),
]
}
}
}
// src/styles/_variables.scss
$sideBarWidth: 180px;
$sideBarBackgroundColor:#2a2935;
$sideBarBorderColor:#1b1b22;
// 某vue文件
<style lang='scss' scoped>
.sidebar-container{
width: $sideBarWidth; // 這里直接使用定義的$sideBarWidth變量,無需引入scss
}
</style>