Hash or prefix all CSS class names in a Vue CLI project to avoid class inheritance

Viewed 2303

I need to hash (or just prefix_) all CSS class names in a Vue CLI project to avoid class inheritance when I embed the app inside an existing HTML page.

Basically the Vue app/widget I've made uses some CSS class names like .title, .container, .date, .location etc, and the problem I've got is that the global CSS on the website where I'm embedding this Vue app already uses the class names .title, .container etc, so it's applying those styles to my Vue app as well. I just want a simple way — maybe using vue.config.js — to instruct webpack to randomly hash or prefix the CSS class names so that they are completely unique and won't inherit any parent styling. Thanks

1 Answers

Thanks to the comments above I managed to get it to work. The implementation is not as straight forward as I'd have liked because it requires changing a lot of my existing code — I was hoping for a quicker, simpler solution that would just take my existing code and hash the preexisting CSS classes — which I'm pretty sure must be possible as it seems like such a trivial task? Anyway, here's my setup for now:

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>

Using the above setup I get a div which, instead of being:

  <div class="myClass"> ... </div>

is now rendered as:

 <div class="_2d736c"> ... </div>

Note the module attribute on the <style> tag which is important. Also note the class name binding: :class (or v-bind:class) not just class.

Hope that helps someone. Thanks

Related