Vue 3 - setting up global Sass/SCSS variables

October 10, 2020

It is very easy to get Vue 3 set up with SCSS/Sass.

I found it a bit of a pain to find instructions on setting up global SCSS/Sass variables with Vue 3 though.

Here are the steps involved. You probably already have a Vue 3 app set up, so can skip some of the first few steps.

Install vue 3

(You can probably skip this step if you have Vue already set up!)

If you have the Vue CLI tool, just run vue create scss and select Vue 3.

There is an option to set up CSS pre processors from the CLI tool but for this article I will ignore that option.

Once set up, cd scss to move into that directory.

Add sass-loader and sass

Run yarn add -D sass-loader sass and get those two critical packages installed.

Once sass is installed, you should be able to update any of your vue single file components CSS style rules from:

<style>
 // (your rules)
</style>

to the following (adding the lang)

<style lang="scss">
 // (your rules - which can now include sass rules)
</style>

We are not quite done yet though, as we have not set up any global Sass rules.

Set up some global sass config for Vue 3:

Currently, if you want to define global variables you would have to include the file in each vue component:

<style lang="scss">
 @import "./scss/_variables.scss"; // $text-primary would be defined in that file

 .your-component {
   color: $text-primary;
 }
</style>

It is much nicer to include some files globally. For this we must create a vue.config.js.

Just run touch vue.config.js from the root directory of your vue app, and then update that file with this:

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

Note: Updated Sept 2022 - from additionalData to prependData.

(Also make sure that you update the prependData string to reference files that you want to include.

After doing this, anything in prependData will be available to use in any of your <style lang="scss">...</style> tags in your Vue components.

See Sass globally set up in a (demo) vue 3 app

I've created a sample Vue application for demo purposes, which has global Sass set up. Take a look at that source code to see it all in action.