VueJS and SASS - Import and use SASS variables in script

Viewed 848

I'm currently working on a VueJS project with a SASS integration, and I would like to get access to the SASS variables inside the script part of the component to make dynamic style calculations. I saw examples of this with pure JS, and I'm trying to translate that to a VueJS component.
So far, I've been able to integrate SASS variables in the style part of the Vue file, but I can't get the variables imported into the script of the component.

I tried the following:
Exporting the variables from my scss file:

:export {
    primaryColor: $primary;
}

And then import the file in my component:

import variables from '@/assets/scss/main.scss'

And access it like so: variables.primaryColor

But I can't get it working, variables is always an empty object with no value inside. I'm using Nuxt with the packages node-sass and sass-loader installed. Any help would be appreciated!

1 Answers

If you want to just access the variables from a SASS file you can add this to configureWebpack in your vue.config.js file:

module:{
  rules: [{
    test: /\.scss$/,
    use: [{
      loader: "style-loader"
    }, {
      loader: "css-loader" 
    }, {
      loader: "sass-loader"
    }]
  }]
}

Then let's say that you have a file containing your SASS variables called style.sass that looks something like this

$btn-color: #D75893

:export
    buttonColor: $btn-color

In your <script> tag you can import your SASS variables file like so

import styleInfo from 'style.sass';

and access your variables like so

console.log("The button color is", styleInfo.buttonColor);

Note: It is not possible to dynamically change SASS variables at run time as the variables are compiled.

Sources: This article from HashRocket and This article from itnext

Related