DEV Community

Cover image for CSS Modules in Nuxt.js
Frida Nyvall
Frida Nyvall

Posted on • Edited on • Originally published at redonion.se

CSS Modules in Nuxt.js

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 learn more about CSS Modules in Vue, see this article.)

To alter the generated class names, edit the nuxt.config.js file:

build: {
    /*
    ** You can extend webpack config here
    */      
    loaders: {
      cssModules: {
        modules: {
          //this is where you can alter the generated class names:
          localIdentName: "[local]--[Frida]_[hash:base64:4]",
        }
      }
    },
  },

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

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

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

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>

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.)

The same approach works for Nuxt projects:

<!--CSS Module styles-->
<template>
   <p :class="$style.classname">Remember to add the classes with js.</p>
</template>

<!--Remember to add the '.module' suffix just before the file extension.-->
<style module src="./filename.module.scss" lang="scss">
    //Note that any other styles here are ignored
    //Only the styles in the src import are being used.
</style>

Start 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).

Top comments (0)