Sharing common CSS across VueJS components

spicydog picture spicydog · Feb 15, 2018 · Viewed 9.4k times · Source

I'm working on the VueJS 2 project and I'm trying to clean the code but struggle with scoped styling.

Here is my requirements. :)

I have 3 components those are very similar to each others, so I decide to use mixins to merge the code into one file. Each component will use that mixins of both template and vuejs. When I want to customize the conditions of a particular component, I can simply override the code in it and it is working fine in this part.

However, one thing that I want to do more is to move the scoped style to the mixins as well. At the moment, the style is wrapped in <style lang="scss" scoped></style> tag and this style works very well on its component but I have to duplicate the styling codes into all 3 components.

I know I can add these styles to the global css file but I don't want some styles to the global scope, only one these 3 components will apply for these.

Is it any way to add these styles and apply to mixins?

What is the best practice to code this particular case?

Answer

M3RS picture M3RS · Mar 7, 2020

Vue makes this easy.

Solution

To use shared styles in a component you can do this.

MyComponent.js

<template>
</template>

<script>
</script>

<style lang="scss" scoped>
  @import '@/scss/shared-styles.scss';
  @import 'styles.scss'; // this is the regular CSS used just by the component
</style>

Alternative

You can also import the shared CSS files in the component CSS file instead like below.

MyComponent.js

<template>
</template>

<script>
</script>

<style lang="scss" scoped>
  @import 'styles.scss';
</style>

styles.scss

@import '@/scss/shared-styles.scss'

// rest of your component CSS

Automatically import global styles

If you want certain styles to be available in ALL your components you can do this.

vue.config.js

module.exports = {
  ...
  css: {
    loaderOptions: {
      sass: {
        prependData: `
          @import "@/scss/global.scss";
        `
      },
    },
  },
}