How to Change Class in HTML with Hash Code and Prefix in Vue 3 Project?

71 views Asked by At

Question: I'm working on a Vue 3 project where I'm using PostCSS to automatically generate hashed and prefixed class names in my CSS files. However, I'm facing an issue when trying to dynamically change the class names in my HTML templates to match the hashed and prefixed class names generated by PostCSS during production builds. How can I achieve this in Vue 3?

Details: In my Vue 3 project, I'm using PostCSS with plugins like postcss-loader and css-loader to generate hashed and prefixed class names in my CSS files during production builds. This helps in preventing CSS class name collisions and ensures better encapsulation of styles.

Here's an example of how my CSS looks after being processed by PostCSS:

/* Before PostCSS processing */
.myClass {
  color: red;
}

/* After PostCSS processing */
._1x2y3z-myClass {
  color: red;
}

Now, during runtime, I need to dynamically change the class names in my HTML templates to match the hashed and prefixed class names generated by PostCSS.

Example: Let's say I have the following HTML template in my Vue component:

<template>
  <div class="myClass">
    Hello, World!
  </div>
</template>

During production builds, I want the myClass to be replaced with the hashed and prefixed class name _1x2y3z-myClass.

Question: How can I dynamically replace the class name myClass in my HTML template with the hashed and prefixed class name _1x2y3z-myClass during production builds in a Vue 3 project?

Some example I found: But I don't want to do like this

vue.config.js

module.exports = {
     css: {
      requireModuleExtension: false,
      loaderOptions: {
       css: {
        modules: {
         localIdentName: '[hash:6]'
        }
       }
      }
     }
    }

my-component.vue

<template>
    <div :class="$style.myClass"> ... </div>
</template>

<style module>
  .myClass {
       color: red;
   }
</style>

Note: I'm looking for a solution that works specifically for production builds and doesn't impact the development workflow.

0

There are 0 answers