Vue 3 provided an in-build CSS-module feature without external configuration.
Lakshmanan Arumugam
Posted on May 13, 2021
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:
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
By default Vue 3 gave two different of composing CSS.
CSS Scoped
Same CSS file and code. but, the class name loads dynamically on render. Refer to the below example:
In scoped CSS have one problem is writing descendant selectors CSS is a little bit have a problem
More info refer itCSS 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).
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>
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>
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
Posted on May 13, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.