vue-cli 3提供了兩種方式集成sass/scss:
創建項目是選擇預處理器sass
手動安裝sass-loader
創建項目選擇預處理器sass
$ vue create vuedemo
? Please pick a preset: (Use arrow keys)
> default (babel, eslint)
Manually select features
移動上下鍵選擇“Manually select features”:表示手動選擇創建項目的特性。
顯示如下:
? Check the features needed for your project: (Press <space> to select, <a> to t
oggle all, <i> to invert selection)
>( ) TypeScript
( ) Progressive Web App (PWA) Support
( ) Router
( ) Vuex
(*) CSS Pre-processors
( ) Linter / Formatter
( ) Unit Testing
( ) E2E Testing
移動上下鍵在CSS Pre-processors,按提示點擊空格鍵選擇CSS-processors。
顯示如下:
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): (Use arrow keys)
> SCSS/SASS
LESS
Stylus
選擇第一個SCSS/SASS作為我們的CSS預處理器。
完成后項目會幫我們安裝sass-loader node-sass。
手動安裝
如果在創建項目沒有選擇CSS 預處理器,我們也可以手動安裝sass-loader node-sass來集成scss。
npm install -D sass-loader node-sass
使用
至此我們只需要在style指定lang為scss即可:
<style lang="scss">
$color = red;
</style>
vue service clie會自動使用我們安裝的sass-loader作為scss內容的加載器。
vue cli是基於webpack構建項目,如果想對sass-loader傳遞一些配置項,可以在vue.config.js配置。在項目的根目錄下如果沒有找到vue.config.js,手動創建即可。如下:
// vue.config.js
const fs = require('fs')
module.exports = {
css: {
loaderOptions: {
sass: {
data: fs.readFileSync('src/variables.scss', 'utf-8')
}
}
}
}
這個文件variables.scss也是可以通過import在.vue組件里引入。