项目中手动增加scss支持
# Vue项目中增加scss支持
# 一、 创建项目时选择预处理器sass
$ vue create vuedemo
? Please pick a preset: (Use arrow keys)
> default (babel, eslint)
Manually select features
1
2
3
4
2
3
4
移动上下键选择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
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
移动上下键在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
1
2
3
4
2
3
4
选择第一个SCSS/SASS
作为我们的CSS
预处理器。
完成后项目会帮我们安装sass-loader node-sass
。
# 二、 手动增加scss支持
网上很多教程直接使用npm install -D sass-loader node-sass
默认最新版本进行安装,安装后发现版本不匹配等问题。遂去npm网站查看历史版本,找到sass-loader@10.2.0
版本、node-sass@4.14.1
下载量最高。卸载后重新安装指定版本发现问题解决。
如果在创建项目的时候没有选择css预处理器,可以手动安装sass-loader
node-sass
来集成scss
npm install -D sass-loader@10 node-sass@4
1
# 三、 在项目中使用scss
完成添加后,我们只需要在style
指定lang
为scss
即可,无须多余操作:
<style lang="scss" scoped>
$color: red;
h1 {
color: $color;
}
</style>
1
2
3
4
5
6
7
2
3
4
5
6
7
# 四、 在项目中引入全局scss文件
# 1. 安装sass-resources-loader
npm i -D sass-resources-loader
1
# 2. 创建scss
文件
在src/assets/styles
中创建base.scss
文件
# 3. 配置vue.config.js
文件
module.exports = {
chainWebpack: config => {
const oneOfsMap = config.module.rule('scss').oneOfs.store
oneOfsMap.forEach(item => {
item
.use('sass-resources-loader')
.loader('sass-resources-loader')
.options({
// Provide path to the file with resources
// 要公用的scss的路径
resources: './src/assets/styles/base.scss'
})
.end()
})
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 4. 在vue文件中直接使用全局scss即可
base.scss:
$test-color:red;
1
xxx.vue:
<style scoped lang="scss">
.home {
.test {
color: $test-color;
}
}
</style>
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
上次更新: 10/21/2021, 1:52:09 PM