Sunday 21 January 2024

How to use CSS modules in vuejs? 114

 How to use CSS modules in vuejs?

Here's a comprehensive guide on how to use CSS Modules in Vue.js:

1. Setup:

  • File Extension: Save your CSS files with the .module.css extension to differentiate them as CSS Modules.

  • Build Configuration: Ensure your build tool (e.g., Webpack) is configured to handle CSS Modules. Vue CLI usually handles this automatically.

2. Importing:

  • Import the CSS Module within your component's JavaScript file:


import styles from './my-component.module.css';

3. Applying Styles:

  • Use the imported object as a class binding in your template:

Code snippet

  <div :class="styles.container">
    <p :class="[styles.title, styles.important]">This is a title</p>

4. Key Points:

  • Local Scope: Each CSS Module creates a unique local scope for its styles, preventing conflicts with other components.

  • Class Name Hashing: Class names are hashed and scoped to the module, ensuring they remain unique throughout the application.

  • No Need for Scoped Attribute: CSS Modules don't require the scoped attribute, as they provide built-in encapsulation.

  • Dynamic Class Names: Hashed class names help avoid naming conflicts and allow for dynamic styling patterns.

5. Additional Examples:

  • Combining Classes:

Code snippet


  • Applying Styles Conditionally:

Code snippet

:class="{ [styles.error]: hasError }"

6. Considerations:

  • Requires Build Tools: CSS Modules rely on build tools for processing and integration.

  • Learning Curve: The import and usage syntax might take some initial learning.

Overall, CSS Modules offer a powerful and flexible solution for style encapsulation in Vue.js projects, promoting better code organization and maintainability.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.