Subscribe to our Newsletter

Get articles, advice and tips about:

You can read more about our privacy policy and how we use your personal data here.

CSS in Nuxt.js

CSS Modules in Nuxt.js

by Frida Nyvall

The second article in a series about working with CSS in Nuxt.js, this time focusing on how to use CSS Modules with Nuxt.

Just like in Vue.js, support for CSS Modules is provided out of the box in Nuxt.js projects. To alter the generated class names, edit the nuxt.config.js file:

build: {
    /*
    ** You can extend webpack config here
    */      
    loaders: {
      cssModules: {
        modules: {
          localIdentName: "[local]--[Frida]_[hash:base64:4]",
        }
      }
    },
  },

In the example above, I’ve added my own name in the middle of the class name.

Use CSS Modules by binding the class name using JavaScript in the template part of the component .vue file:

<template>
    <section>
        <h1 :class="$style.moduleclass">Contact</h1>
    </section>
</template>

Add the module keyword to the style section of the component file:

<style module lang="scss">
    .moduleclass{
        color: green;
    }
</style>

It is also possible to use CSS Modules for just some and not all of the components in a project. Check out the documentation on how to set up opt-in usage.

Importing Module Style Files

In Vue.js projects, it is possible to put styles in a separate filename.module.css file and import it in the script tag of a .vue file. (See the article “CSS Modules in Vue.js” for more info.)

This does however not seem to work in the same way for Nuxt.js projects, at least not judging from the tests I did with a project setup as described below.

Setup

Note that both setup, plugins and framework are evolving. Changes will in time most certainly happen that make the techniques described in this post less relevant.

I’ve used create-nuxt-app version 2.10.0 to set up the project. When setting up the project, I chose NPM as package manager and jsconfig.json as development tool (only choice available and recommended for VS Code).

Articles in this series

Tags

More posts

img

All about webP images

img

CSS Special Effects

img

CSS Filters