一、安装
安装 sass
、 node-sass
和 sass-loader
npm install sass node-sass sass-loader
如果安装失败可以使用 淘宝镜像
或者 cnpm
,淘宝镜像和cnpm安装方法
sass-loader
是为了让 webpack
、vite
等打包工具加载 Sass/SCSS
文件并将他们编译为 CSS
注意:node-sass
必须和 node.js
版本相匹配,否则项目无法运行
附:node-sass
和 node.js
版本对照表,本文只列举一部分,详细内容可以去 node-sass官网 查看
NodeJS | Supported node-sass version | Node Module |
---|---|---|
Node 19 | 8.0+ | 111 |
Node 18 | 8.0+ | 108 |
Node 17 | 7.0+, <8.0 | 102 |
Node 16 | 6.0+ | 93 |
Node 15 | 5.0+, <7.0 | 88 |
Node 14 | 4.14+ | 83 |
Node 13 | 4.13+, <5.0 | 79 |
二、使用
1. 创建一个 scss
文件
假设在 src/assets/style/
文件中创建了一个叫 index.scss
的文件
2. 引入文件
局部引入
在 .vue
文件中引入
.vue
<script>
import "@/assets/style/idnex.scss";
export default {
};
</script>
<style lang="scss" scoped>
</style>
全局引入
在 main.js
中引入
main.js
import "./assets/style/idnex.scss";
3. 引入变量、混入
按照上面的方法引入变量是不会生效的,scss变量
需要在 打包工具
中配置,如 vue.config.js
、vite.config.ts
举例:在 src/style/
文件夹中创建 color.scss
、mixin.scss
文件
color.scss
// 颜色变量
$red: #ff3c3c;
$orange: #ff9302;
$yellow: #fecf03;
$blue: #2e6cf6;
$green: #5cc9a5;
mixin.scss
// 混入-滚动条样式
@mixin scroll-bar {
&::-webkit-scrollbar-track-piece {
background: #d3dce6;
}
&::-webkit-scrollbar {
width: 6px;
}
&::-webkit-scrollbar-thumb {
background: #99a9bf;
border-radius: 20px;
}
}
注意:在不同的打包工具中引入,配置是不一样的
vue.config.js
module.exports = {
// ...
css: {
loaderOptions: {
sass: {
prependData: `@import "@/style/color.scss"; @import '@/style/mixin.scss';`,
},
},
},
};
vite.config.ts
export default defineConfig( {
css: {
preprocessorOptions: {
scss: {
additionalData: `@import '@/style/color.scss'; @import '@/style/mixin.scss';`
},
}
}
})
4. 使用
经过上面的方法引入后,即可在全局使用配置好的变量和混入了,使用方法如下
<style lang='scss' scoped>
.header {
background-color: $blue;
}
.main {
@include scroll-bar;
width: 100%;
height: calc(100vh - 66px);
padding: 20px;
overflow: auto;
}
</style>