How to @extend sass classes or use sass global variables in Vue components

Extend classes and use of variables are two of the sass most powerful tools. But using them in a VueJS application could be a little bit tricky. In this article, I will show you a way of using these two on components without the need for importing the sheet containing them at each usage.

Let’s assume that you have a class that you want to extend

src/styles/style.scss

.my_class_to_extend {
  backgroud-color: aqua;
}

Assuming you generated your project with @vue/cli, you have to add the following statement to vue.config.js in order to have file visibility throughout your application

module.exports = {
  css: {
    loaderOptions: {
      sass: {
        data: `@import "@/styles/style.scss";`
      }
    }
  }
}

Then, you can use @extend on which component you want

<style lang="scss" scoped>
.my_extended_class {
  @extend .my_class_to_extend;
}
</style>

Remember that you have to use sass in both extended and extender sheets for this to work.

Leave a Reply

Your email address will not be published. Required fields are marked *