Using sass variables in a VueJS component

I'm using the latest version (v9.0.2) of sass-loader, and prependData doesn't seem like an option now. You might want to try this configuration in vue-config.js. Notice the additionalData option is being used as there's no longer a prependData option.

module.exports = {
  css: {
    loaderOptions: {
      sass: {
        additionalData: '@import "@/pathto/variables.scss";'
      }
    }
  }
}

Importing the _variables.scss in every component seems to be the only solution I've found so far (it should work, according to this issue).

<template>
    <div class="my-color"></div>
</template>
<style lang="sass">
    @import 'path/to/your/_variable.scss'; // Using this should get you the variables
    .my-color {
        color: $primary-color;
    }
</style>
<script>
    export default{
        data(){
            return {}
        }
    }
</script>

As you are only going to include variables, this shouldn't be a problem.

But as mentioned in the issue, a word of caution: You should only include abstract entities (variables, extends, mixins) into every component, no concrete CSS rules.


Assuming you are using vue-cli, try this.

If you don't already have the sass loader installed:

npm install -D sass-loader node-sass

Then in vue.config.js:

const path = require('path');

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

In your component:

<style lang="sass">
    .my-color {
        color: $primary-color;
    }
</style>

Source:

  • Passing options to pre-processor loaders

  • How to import a sass file into every vue component

Edit:

As of sass-loader 8, data needs to be prependData (Thanks to @ben-y for pointing this out):

const path = require('path');

module.exports = {
  css: {
    loaderOptions: {
      sass: {
        prependData: `@import "@/pathto/variables.scss";`
      }
    }
  }
};