Vue2和Vue3中的Sass使用、node-sass、sass-loader

给大家介绍一下sass相关的操作。Sass (Syntactically Awesome Style Sheets)是一种流行的预处理器脚本语言,用于扩展CSS的功能。它提供了许多功能,使编写和维护CSS代码更加容易。在本文中,我们将讨论如何在Vue2和Vue3版本中使用Sass。

作为前端开发,经常接手项目安装依赖时出问题,我先来列举一下对应关系。对应以下是 node-sass、sass-loader 和 Node.js 的对应版本:

| Sass 工具 | 支持的 Node.js 版本 | 支持的 sass-loader 版本 |

| -------- | -------------------- | ------------------------ |

| node-sass | 0.10.x - 6.x | ^4.0.0, ^7.0.0 |

| sass | 8.x.x - latest | ^11.0.0 |

| sass-loader | 3.x.x - 12.x.x | 6.0.0 - latest |

| Node.js | 8.x.x - latest | - |

Vue2中的Sass

Vue2提供了Sass的内置支持。在Vue2中使用Sass有两种方法:

1. 全局使用

要在Vue2中全局使用Sass,请使用以下命令安装sass-loadernode-sass包:


npm install sass-loader node-sass --save-dev

安装这些包后,在项目的根目录中创建一个名为vue.config.js的文件,并添加以下代码:


module.exports = {

  css: {

    loaderOptions: {

      sass: {

        data: `@import "@/styles/main.scss";`

      }

    }

  }

};



//由于sass-loader的版本不同,不同的版本对应的关键字:

//sass-loader v8-中,关键字为 “ data ”

//sass-loader v8中,关键字为 “ prependData ”

//sass-loader v10+中,关键字为 “ additionalData ”

这个代码将把main.scss文件导入到你Vue2项目的所有组件中。

2. 作用域使用

你还可以通过将以下代码添加到组件中,在Vue2中按照组件使用Sass:


<template>

  <div class="demo-component">

    <!-- Component HTML code here -->

  </div>

</template>

<script>

export default {

  // Component configuration options

};

<style lang="scss" scoped>

.demo-component {

  // Sass code for the component

}

</style>

在这里,我们使用scoped属性,将我们的Sass代码应用于组件的HTML元素。

Vue3中的Sass

Vue3也提供了对Sass的内置支持。你可以像在Vue2中使用Sass一样在Vue3中使用Sass,但有一些不同之处。

1. 全局使用

要在Vue3中全局使用Sass,请使用以下命令安装sasssass-loader包:


npm install sass sass-loader --save-dev

安装这些包后,在项目的根目录中创建一个名为vite.config.js的文件,并添加以下代码:


import { defineConfig } from 'vite';

import vue from '@vitejs/plugin-vue';

export default defineConfig({

  plugins: [vue()],

  css: {

    preprocessorOptions: {

      scss: {

        additionalData: `@import '@/styles/main.scss';`

      }

    }

  }

});

这个代码将把main.scss文件导入到你Vue3项目的所有组件中。

2. 作用域使用

在Vue3中,scoped属性已被module属性替换。你可以通过将以下代码添加到组件中,在Vue3中按照组件使用Sass:


<template>

  <div class="demo-component">

    <!-- Component HTML code here -->

  </div>

</template>

<script>

export default {

  // Component configuration options

};

<style lang="scss" module>

.demo-component {

  // Sass code for the component

}

</style>

在这里,我们使用module属性,将我们的Sass代码应用于组件的HTML元素。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容