Search code examples
cssvue.jssassvuejs3vite

:root variables not registering in SCSS and Vue3 using Vite


I am trying to set variables in my root SCSS file and they are not registering properly

In my Vite config I have the following to import my styling:

css: {
  preprocessorOptions: {
    scss: {
      additionalData: `
        @use "./src/styles/main.scss";
      `
    }
  }
}

In my main.scss file I have the following:

:root {
  --test: #ff0000;
}

* {
  background-color: var(--test);
}

Whenever I run the code and look in the inspector it shows: '--test is not defined), when hovering over the variable.

However, when I remove the variable and directly set background-color: #ff0000, it does work, so it's just that the :root variables are not being registered.

What could be the issue?


Solution

  • I think, the way you want to implement the styling is not the best way to do it. If you have a global style, that you want to apply to the Vue application, you should import the css either inside your App component or import it inside the main.ts file like:

    import './styles/main.scss'.
    

    The reason for that is, that the style you use in additionalData will be applied to all files which means, you will have this styles applied to all generated css files.

    The vite configuration documentation explains it like:

    All preprocessor options also support the additionalData option, which can be used to inject extra code for each style content. Note that if you include actual styles and not just variables, those styles will be duplicated in the final bundle.

    I think, if you import it as described, you might not have this issue anymore.