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.
I'm wondering what is causing this behaviour?
And this is the huge problem of css. To avoid this problem Vue allows us to make our css isolated and only valid for this component. To achieve that we need to add scoped attribute to our styles section. As you can see everything is working as before but we have a special class notation now.
To add global CSS in Vue.js, we can import our global CSS file in main.js. to import the styles in ./assets/css/main.css globally. To add global CSS in Vue.js, we can import our global CSS file in main.js.
If inline styles is overriding our CSS, then they must have some bookmarklet, script, which iterates over some specific elements and manipulates the style attribute. But, again, I don’t see this happening.
An !Important declaration is a great way to override the styles you want. When an important rule is used on a style declaration, this declaration will override any other declarations. When two conflicting declarations with the !important rules are applied to the same element, the declaration with a greater specificity will be applied.
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'
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With