Efficiently managing classes with css modules and extractCSS in Nuxt 2

When using Nuxt 2 with CSS modules, I encountered an issue where multiple components resulted in multiple CSS files having the 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>

As a result, both files contain the same class .YT3xv.

This raises the question of whether there is a solution to this problem. Ideally, I would like to extract these classes into a separate file.

Answer №1

To streamline your project, consider creating a dedicated CSS file (e.g., shared.css) to define common classes that can be used across different components.

Your project structure may look something like this:

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

In the shared.css file, define your shared classes:

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

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

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

Next, import shared.css in your component files:

<!-- 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>

This setup allows Nuxt.js to automatically extract the common classes from shared.css into a separate CSS file during the compilation process.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When using `setState()`, ensure that you are updating a component that is already mounted or in the process of mounting. If you receive this error, it

When using WebSocket to communicate with my server, I call the handleSubmit() function to send data and update my state based on the received response. Everything works fine initially. Upon calling componentWillUnmount, I stop sending data to the websocke ...

Leveraging route configuration's scope in HTML

As a beginner in AngularJs, I am currently exploring the creation of a single page application. However, I am encountering difficulties in converting my initial code into more professional and efficient code. During this conversion process, I have separate ...

Is Javascript Profiling a feature available in Firebug Lite?

Exploring the world of JavaScript profiles, I decided to step away from the usual Chrome Developer tools. Can Firebug Lite for Google Chrome provide Javascript Profiling functionality? ...

Warning from Vue: Steer clear of directly changing a prop as it will be replaced whenever the parent component undergoes re-rendering

I've been diving into Vue.js, but I'm encountering an issue. Every time I try to click on the "edit age" or "change my name" button, I get the following error message. [Vue warn]: Avoid mutating a prop directly because the value will be overwrit ...

Encountering the "Error: JSON.parse: unexpected character" when trying to retrieve JSON data using AngularJS

I've been struggling with this issue for the past few days. Every time I attempt to fetch a JSON object using Angular's $http.get method, I encounter the error message "Error: JSON.parse: unexpected character". The JSON data is generated using P ...

Address the snack bar problem

In my quest to create a custom snackbar, I have encountered a minor issue with setting and deleting session variables in Node.js. While using global or local variables works well for accessing data on the client side, there is a chance of issues when multi ...

Exploring the Power of Observables in Angular 2: Focusing on Targeting an Array Nested Within

I encountered a situation where I was successfully looping through objects in an array within my Angular 2 application using observables. In the client service file, my code looked like this: getByCategory(category: string) { const q = encodeURICompon ...

Error code -4058 ENOENT indicates that the file or directory does not exist. This issue is usually caused when npm is unable to locate a specific file

Trying to start a react project on my D: drive while having node installed on the C: drive resulted in an error: D:\react> npm start npm ERR! code ENOENT npm ERR! syscall open npm ERR! path D:\react/package.json npm ERR! errno -4058 npm ERR! ...

The JQuery function fails to execute following a successful Ajax request

I recently ran into an issue with my Ajax call. Here's the code snippet in question: $("#start-upload-btn").click(function(){ $.ajax({ type: "post", url: "", data: { newProjectName: $('#project-name') ...

Restful Spinner

app.config(function(RestangularProvider) { RestangularProvider.addRequestInterceptor(function(element) { console.log("Request initiated"); return element; }); RestangularProvider.addResponseInterceptor(function(data) { ...

Is there a way to prevent the jsonPayload in stackdriver from automatically converting to a struct format?

When working with a Google Cloud Function, I am logging a simple JSON structure like this: console.info(JSON.stringify({message: 'xxx', data: {status: 200}, status: 200})); However, the log appears in an unreadable format in Stackdriver. How ca ...

Executing functionality based on changes in Angular bindings

I am working on securing user passwords in my HTML form. Currently, the password field is stored in localstorage like this: In JS: $scope.localStorage = localStorage; And then in HTML: <input id="pass" type="password" ng-model="localStorage.pass" re ...

Switching Primary Menu Selection When Scrolling Through Various Menu Options

I need help with changing the active class of links on my single page scrolling website. I found some useful code snippets for smooth scrolling and updating the active class on scroll or click events: $(document).ready(function () { $(document).on(" ...

Navigating through various versions of admin-on-rest can be perplexing

This question is likely directed towards maintainers. Currently, I am using the stable version of admin-on-rest (https://www.npmjs.com/package/admin-on-rest) which is at 1.3.4. It seems that the main project repository is only receiving bug fixes, while ...

Unravel and extract information from a JavaScript object using PHP

I am working with a variable called "type" in my code. var type = []; Within this variable, I am using the method push to add an object {'type' : 1}. type.push({'type' : 1}); After performing this operation, I end up with the follow ...

The require() function is not functioning properly, even after I tried switching the type from module to common. As a newcomer to this, there may be something essential that I

Despite changing the type from module to common, I am still unable to get require() to work. As a newcomer to this, there may be something I'm overlooking that I can't quite pinpoint. I attempted const express = require('express'); but ...

Utilizing Stripe for Payment Processing

I'm encountering a problem with getting Stripe charging to function properly. Despite having manually loaded Composer since it wouldn't install, I am not receiving any PHP errors and the token creation is running smoothly. There don't seem t ...

What is the best way to integrate Angular 5 with various sources of JavaScript code?

I am fairly new to angular. I am looking to merge an external angular script file and on-page javascript code with angular 5. I understand that angular does not typically allow for the inclusion of javascript code in html components, but I believe there m ...

A guide on sending arrays from javascript to a Laravel controller through axios

Currently, I am utilizing Laravel 5.4 and Vue 2 to manage my data. I am facing an issue where I need to call a controller method using axios while passing two arrays. These arrays are crucial for making database requests in the controller and retrieving ne ...

Determine line-height and adjust positions using JavaScript in the Chrome browser

I am creating a basic text reading application with a line to aid in easy reading. The functionality involves using the up and down arrow keys on the keyboard to adjust the position of a red line based on the line-height property. This is accomplished thr ...