2
votes

I'm building an App with Vue.js and CSS Components. There are some Vue components, which share common styling.

Hello.vue:

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

GoodBye.vue:

<template>
  <div :class="$style.title">Goodbye, cruel world.</div>
</template>
<script>
export default {}
</script>
<style module src="./common.css"></style>

common.css:

.title {
  font-weight: bold;
}

When I compile and run this code, there are a duplicated CSS class(._2miFMUAEBLdLB9wHpgrYF2):

Screenshot: Duplicated CSS classes

How can I fix this duplication?

Complete code is available here: https://github.com/ryo-utsunomiya/css-modules-common-style

1
Just a guess: Include the CSS file in the pages that use the components, not inside the components themselves?PatrickSteele
Thank you for giving suggestions. In fact, the scope of $style is component. We must somehow inject parent's $style into child components(like Bill Criswell's idea: this.$commonStyles).ryo

1 Answers

0
votes

I was just digging into this last night! I'm still working on understanding the best approaches but I'll share what I've discovered so far.

What you have will output the same css twice in dev mode, but in production it is deduped thanks to this in the webpack.prod.conf.js file.

new OptimizeCSSPlugin({
  cssProcessorOptions: config.build.productionSourceMap
  ? { safe: true, map: { inline: false } }
  : { safe: true }
}),

However, this still adds duplicate hashes to your app.js to map the real class name to the module class name which can bloat up quick. This is true even if you name it.

The approach I'm leaning towards for now is just having a common stylesheet included in the root component with a simple non-scoped non-module style and the component will just have its own unique styles in it with module. You would just use the plain class names from common.

However, another approach I'm considering is doing this in my root component:

<style module="$commonStyles" src="./common.css"></style>

Then making this.$commonStyles available throughout the app.

I'll let you know where I end up.