DEV Community

Cover image for Use Sass Variables in Javascript

Use Sass Variables in Javascript

JS & Rust dev, architect for Tauri, security engineer
Updated on ・2 min read

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

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()

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"

4) Update your SASS file:

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

@import "./quasar.variables.json"

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

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']

7) Relax!

Image from Unsplash:

Discussion (1)

kimsean profile image
Kim Sean Pusod • Edited

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