Classes duplication with css modules and extractCSS in Nuxt 2

56 Views Asked by At

I use nuxt 2 with css modules and when i use one css module with multiple components it results in then multiple css files have same class

Hello.vue

<template>
  <div :class="$style.title">Hello, World</div>
  <div :class="$second.secondClass">Hello, World</div>
</template>
<script>
export default {}
</script>
<style module src="./hello.css"></style>
<style module="$second" src="./uncommon.css"></style>

Goodbye.vue

<template>
  <div :class="$style.title">Goodbye, World</div>
  <div :class="$second.secondClass">Goodbye, World</div>
</template>
<script>
export default {}
</script>
<style module src="./goodbye.css"></style>
<style module="$second" src="./uncommon.css"></style>

and as a result i have two files with content

enter image description here

enter image description here

where in both files i have same class .YT3xv

Can i do something about it? in perfect scenario i would like to extract classes like that in separate file

1

There are 1 best solutions below

0
Mohesn Mahmoudi On

You can Create a separate CSS file (shared.css, for example) where you define the shared classes.

I think your project structure is something like this:

- assets
  - css
    - shared.css
- components
  - Hello.vue
  - Goodbye.vue
- nuxt.config.js

In shared.css, define your shared classes:

/* shared.css */
.sharedClass {
  /* styles */
}

In your nuxt.config.js, specify the extractCSS option to extract CSS into a separate file:

// nuxt.config.js
export default {
  // other configurations
  build: {
    extractCSS: true
  }
}

Then, in your components, import shared.css:

<!-- Hello.vue -->
<template>
  <div :class="$style.title">Hello, World</div>
  <div :class="$style.sharedClass">Hello, World</div>
</template>

<script>
export default {}
</script>

<style module src="./hello.css"></style>
<style src="~/assets/css/shared.css"></style>
<!-- Goodbye.vue -->
<template>
  <div :class="$style.title">Goodbye, World</div>
  <div :class="$style.sharedClass">Goodbye, World</div>
</template>

<script>
export default {}
</script>

<style module src="./goodbye.css"></style>
<style src="~/assets/css/shared.css"></style>

With this setup, Nuxt.js will automatically extract the shared classes defined in shared.css into a separate CSS file during the build process.