16

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?

2 Answers 2

16

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'
Sign up to request clarification or add additional context in comments.

3 Comments

For me this causes class selectors in the global scss to stop working.
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!
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.
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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.