Home > OS >  Vue 3 (CLI) imports global styles many times than need
Vue 3 (CLI) imports global styles many times than need

Time:04-05

So, I have scss file with global styles. This file seems like that:

@import "colors";
@import "border-radius";
@import "box-shadow";
@import "paddings";
@import "margins";
@import "fonts-famalies";
@import "font-sizes";
@import "transition-durations";
@import "global-path";

@import "mixins";
@import "mixins-properties";

@import "../design/animations/fade-animation";

::v-global(*), ::v-global(*::before), ::v-global(*::after) {
  box-sizing: border-box;
  outline-color: var(--color-outline__global);
  transition: background-color 0.2s linear;
}

::v-global(html), ::v-global(body), ::v-global(#application) {
  font-family: var(--font-famaly__comfortaa);
  background-color: var(--color-background__global);
  color: var(--color-font__content);
  margin: 0;
  font-size: 95%;
  height: 100vh;
  overflow-wrap: anywhere;
}

v:global(a) {
  color: var(--color-font__link);
}

Styles imports using vue.config.js with this configuration:

module.exports = defineConfig({
  transpileDependencies: true,

  css: {
    loaderOptions: {
      sass: {
        additionalData: `
          @import "@/styles/global/global.scss";
        `
      }
    }
  }
})

All good, but when I open developer console in chrome I see picture like that. When I checked header tag in HTML I see a lot of same css imports. If I comment all css styles - header have a lot of styles still. What am I doing wrong? I think that problem in loader

CodePudding user response:

If you're going to be adding a global import (for example for shared SCSS variables and mixins), don't put ANY global styles in that import.

scss-loader's additionalData modifies each scss file it loads with the given string template. As a result, you're putting an import with your global style definitions at the start of every component's style block.

To fix this, move all your v-global(html) styles and the animations to a different file, which you import once in your index.html or App.vue. Ensure that the file you want to automatically import in your components only contains code that does not generate any styles by themselves (so scss variables, mixins, functions, etc. are fine). It's common that you name this file 'variables.scss' or similar, so no style definitions accidentally end up in this file or its dependencies.

  • Related