DEV Community

loading...
Cover image for Vue 3 provided an in-build CSS-module feature without external configuration.

Vue 3 provided an in-build CSS-module feature without external configuration.

Lakshmanan Arumugam
My passion is building an impressive and beautiful web application through carefully crafted code with user-centric design.
・2 min read

In every web application maintaining a CSS code is a little bit difficult. When growing the CSS files and codes in the project. it's solved by using different methods.

There methods are:

  1. SCSS/SASS
  2. LESS
  3. Stylus
  4. CSS-Modules
  5. CSS-in-JS

Each method has pros and cons. but, now I am not going to explain each of the method's pros and cons. Now, here I only explain what's CSS-module and how to use it on Vue 3.

What in CSS-module?

It is basically the same as the CSS code structure and all. The main difference is calling methods is too different. In a simple way we say:

CSS-Modules = CSS in JS objects
Enter fullscreen mode Exit fullscreen mode

By default Vue 3 gave two different of composing CSS.

  1. CSS Scoped
    Same CSS file and code. but, the class name loads dynamically on render. Refer to the below example:
    Alt Text
    In scoped CSS have one problem is writing descendant selectors CSS is a little bit have a problem
    More info refer it

  2. CSS Module
    Same CSS file and code. but, rendering and showing class name as dynamically and we able to customize the class name based on environment(Dev mode and production mode).
    Alt Text

why we consider the CSS module in Vue 3?

  • Using CSS modules to avoid namespace collision for CSS classes
  • You can confidently update any CSS file without worrying about affecting other pages

I think it's enough for now. because these 2 have major problems in CSS. Even more, advantages have CSS modules.

Using CSS modules in Vue

Step 1:
Write a CSS inside the style of the component like below. Inside the style tag should module attribute.

<style module>
  .svg_icon {
    fill: currentColor;
    height: 24px;
    width: 24px;
  }
</style>
Enter fullscreen mode Exit fullscreen mode

Step 2:
Use the class name inside the template HTML code. using $style variable. Like below:

<template>
  <svg :class="[$style.svg_icon]" xmlns="http://www.w3.org/2000/svg">
    <title v-if="title">{{ title }}</title>
    <use :xlink:href="iconPath" xmlns:xlink="http://www.w3.org/1999/xlink"/>
  </svg>
</template>
Enter fullscreen mode Exit fullscreen mode

That's all the CSS-module successfully use in the Vue component. Code Repo URL

Reference:
CSS Modules Configuration.
Love CSS Modules in Vue.js

Discussion (0)

Forem Open with the Forem app