Automatically import SCSS file for every Vue component

156 Views Asked by At

I trying do import globally an variables.scss file

my vue.config.js like the following:

module.exports = {
        css: {
            loaderOptions: {
                scss: {
                    additionalData: `@import "@/styles/variables.scss";`
                },
            }
        }
}

variables.scss

$dark-bg: #1C2537;

and vue file where i try use it

<script setup>
// Component logic
</script>

<template>
    <!-- Template -->
</template>

<style lang="scss">
@import "@/styles/variables.scss"; // if i add this all works
.left-menu {
  background-color: $dark-bg;
}
</style>

when i directly import variables.scss in vue file all work good but global import not works

if any idea what problem is?

i use: "sass": "^1.69.5", "sass-loader": "7.3.1", "vue": "^3.2.26",

i expect my variables from variables.scss works globally in all vue files

2

There are 2 best solutions below

4
Laurent Schoelens On BEST ANSWER

I've quite similar configuration but the only thing that differs from yours is the scss property which is `sass :

Syntax for sass-loader v9 and above :

    loaderOptions: {
      sass: {
        additionalData: `
          @use "sass:math";
          @import "@/css/_colors.scss";
          @import "@/css/_animations.scss";
          @import "@/css/_mixins.scss";
        `
      }
    }

In my .vue file I can do then the following with no errors :

<style lang="scss">
  .message {
    color: $error-color;
  }
</style>

Since, according to documentation, sass options also applies to scss options, maybe you could give it a try ?

My declared version of vue / sass and sass-loader in package.json :

    "vue": "^3.2.47",
    "sass": "^1.51.0",
    "sass-loader": "^12.6.0"

Important note in documentation : this option is named as prependData in sass-loader v8

EDIT After digging more since we have some differences in sass-loader versions, I found that you should use the data option, as suggested by Alex in the comments

See changelog v8 where they say that

the data option was renamed to the prependData option

And then see changelog v9 where they say that

the prependData option was removed in favor the additionalData option, see docs

So here is correct syntax for v8 sass-loader (working with scss or sass loaderOptions) :

    loaderOptions: {
      scss: {
        prependData: `@/styles/variables.scss";`
      }
    }

For v7 and below :

    loaderOptions: {
      scss: {
        data: `@/styles/variables.scss";`
      }
    }

And for v9 and above

    loaderOptions: {
      scss: {
        additionalData: `@/styles/variables.scss";`
      }
    }
0
Alex On

You can add the file path to your scss file in your vue.config.js file. Here is an example:

module.exports = {
  css: {
    loaderOptions: {
      scss: {
        additionalData: `@use "@/assets/scss/variables/variables.scss" as *;`
      },
    },
  },
};