14

In my vue project I have some globally defined css, like a reset file etc. I load this css using the following in my vue.config:

css: {
  loaderOptions: {
    sass: {
      data: `
        @import "@/assets/styles/styles.scss";
      `,
    },
  },
},

When i look in the browser styles it seems like the css is overwriting itself 50+ times.

screenshot

I'm wondering what is causing this behaviour?

jordvand9
  • 159
  • 2
  • 6

2 Answers2

15

In your vue.config.js put only variables, mixins, functions.

module.exports = {
  css: {
    loaderOptions: {
      sass: {
        data: `
          @import "@/assets/sass/_colors.scss";
          @import "@/assets/sass/_variables.scss";
          @import "@/assets/sass/_mixins.scss";
          @import "@/assets/sass/_functions.scss";
        `
      }
    }
}

Now, in styles.scss put your styles, for instance:

@import "reset";
@import "base";
@import "fonts";
@import "z-index";
@import "transitions";
@import "util";

In your main.js import styles.scss

import '@/assets/styles/styles.scss'
  • For me this causes class selectors in the global scss to stop working. – Deji Feb 04 '21 at 13:23
  • It solves the problem but as Deji described, we lose the ability to extend the classes that were described in styles.css, and I would like to keep this functionality! – Bruno Tavares Feb 16 '21 at 09:10
  • Using Vue3/Nuxt 3, I had to import the "styles.scss" in my "app.vue". The other files I imported in the nuxt.config.ts - using vite the import is placed in vite.css.preprocessorOptions.scss there. Note, that you still can group the variables/function/mixins into one single file and import that instead of multiple files in the vue.config. Additionally I had to import them in my "histoire.setup.ts" to make them available there as well, since that doesn't use the app.vue. Should probably work similar if using storybook. – Benedikt Böhm May 27 '23 at 21:09
4

Your global styles file is being attached before the style block of every component that your router.js is importing.

As a result, there are many definitions of the same css class, which look like they are being overridden.

One simple way to reduce the clutter is to enable lazy loading of the components as has been described in the documentation here -> https://router.vuejs.org/guide/advanced/lazy-loading.html

In order to implement this you would have to alter only the import statements in router.js and absolutely nothing will need to be changed anywhere else.

If I were to give a silly example:

import Foo from "@/src/views/Foo.vue";

would become

const Foo = () => import('@/src/views/Foo.vue');
Anuvrat Parashar
  • 2,960
  • 5
  • 28
  • 55