DEV Community

Cover image for Use Sass Variables in Javascript
Daniel Thompson-Yvetot for Tauri

Posted on • Edited on

Use Sass Variables in Javascript

Sass variables are awesome in that they guarantee that you are using the right colors, dimensions, animations etc. everywhere in your Webapp. It is, unfortunately, not very straightforward to access them in Javascript - and using them from Tauri is an exercise in mind-bending futility.

This is a little writeup about a nice and easy solution for accessing Sass variables in your Javascript.

For this tutorial, we are going to assume you already have Sass working in your project. We're going to be using the VueJS based Quasar Framework, but the same principle should work with other frameworks as well.

1) Add the dependency

We don't need to ship this, as we are going to be using it only at build time.

yarn add --dev node-sass-json-importer
Enter fullscreen mode Exit fullscreen mode

2) Update your webpack config

Quasar has a special build setting in quasar.conf.js that you can easily modify:

const jsonImporter = require('node-sass-json-importer')
module.exports = function (ctx) {
  return {
    ...
    build: {
      ...
      sassLoaderOptions: {
        sassOptions: {
          importer: jsonImporter()
        }
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

3) Create your variables

You can save your settings as JSON in src/css/quasar.variables.json. Of course you can add whatever you want here, just be sure not to repeat these keyValues in your real SASS file.

{
    "primary": "#3215B3",
    "secondary": "#29269A",
    "accent": "#9C27FF",
    "info": "#3100EC",
    "spotColor" "#C0FF33"
}
Enter fullscreen mode Exit fullscreen mode

4) Update your SASS file:

Replace your src/css/quasar.variables.sass with the following:

@import "./quasar.variables.json"
Enter fullscreen mode Exit fullscreen mode

5) Create and register a bootfile src/boot/sass.js

With quasar you can put this in a bootfile.

import sass from '../css/quasar.variables.json'

export default ({ Vue }) => {
  Vue.prototype.$sass = sass
}

export { sass } // in case you need it outside of vue
Enter fullscreen mode Exit fullscreen mode

Don't forget to register the bootfile in your quasar.conf.js!

6) Use your sass variable in a Vue SFC:

Of course this is just one thing you can do, the approach will work for any number of other things.

  methods: {
    sassColor (colorName) {
      return this.$sass[colorName]
    },
    sassSpotColor () {
      return this.$sass['spotColor']
    }
  }
Enter fullscreen mode Exit fullscreen mode

7) Relax!


Image from Unsplash: https://unsplash.com/photos/M6lu8Wa72HQ

Top comments (1)

Collapse
 
kimsean profile image
thedevkim • Edited

Thank you! it makes easier on implementing user based theming. Nice!