VueJS

How to Style Using SCSS in Nuxt

Adesoji Temitope
2 min read
How to Style Using SCSS in Nuxt
This article was written over 18 months ago and may contain information that is out of date. Some content may still be relevant, but please refer to official documentation for the latest information.

Introduction

SASS makes working on large projects more organized. It allows you to use variables, nested rules, mixins, and functions. The preferred styling method in Nuxt is component file styling, and integrating SASS into your project can make your component file styling appear more understandable.

How to Import SASS in Nuxt

To add SASS after setting up your Nuxt application, we will first install SASS and sass-loader. Let's run either of these commands depending on our package manager.

$ yarn add sass sass-loader --dev
# or
$ npm install sass sass-loader --save-dev

Component File Styling

With SASS and sass-loader installed in our project, we can now write SCSS in our component file.

Lets see an example:

<!-- src/components/button/button.vue -->
<template>
    <button
        class="app-button"
    >
      <slot></slot>
    </button>
</template>

<style lang="scss">
  .app-button {
    position: relative;
    display: inline-flex;
    cursor: pointer;
    text-align: center;
    white-space: nowrap;
    align-items: center;
    justify-content: center;
    vertical-align: top;
    text-decoration: none;
    outline: none;

    // variant
    &--primary {
        background-color: #0e34cd;
        color: #ffffff;
    }
}
</style>

In the example above, all we need to specify is lang="scss" on the style tag, and we can now write scss in that component.

Global File Import and Variables

To import SCSS files that are global, like variables and mixins files, we need to install style-resources:

$ yarn add @nuxtjs/style-resources --dev
# or
$ npm install @nuxtjs/style-resources --save-dev

Next, we can update our nuxt.config.js file by adding the module we just installed to the buildModules.

// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [
  '@nuxtjs/style-resources',
],

Next, let's create a global variables.scss file in our assets/style folder.

Add a single variable inside:

// assets/style/variables.scss

$primary: #010933;
$white: #fff;

Next, we need to import this file inside the nuxt.config file:

 styleResources: {
    scss: [
      '~/assets/style/variables.scss',
    ],
  },

Now we have the variables in our variables.scss available in all our components for use.

Next, let's test it out by updating our button component.

<!-- src/components/button/button.vue -->
<template>
    <button
        class="app-button"
    >
      <slot></slot>
    </button>
</template>

<style lang="scss">
  .app-button {
    position: relative;
    display: inline-flex;
    cursor: pointer;
    text-align: center;
    white-space: nowrap;
    align-items: center;
    justify-content: center;
    vertical-align: top;
    text-decoration: none;
    outline: none;

    // variant
    &--primary {
        background-color: $primary;
        color: $white;
    }
}
</style>

We have updated our button variant color to be our global SCSS variable ($primary and $white).

Mixins

Mixins in SASS are used to write styles that can be reused in other parts of the code.

Let's create a sample mixin to center an item.

// assets/style/mixins.scss

@mixin center-item {
  text-align: center;
  align-items: center;
  justify-content: center;
}

Next, we need to import our mixin in Nuxt config:

 styleResources: {
    scss: [
      '~/assets/style/variables.scss',
      '~/assets/style/mixins.scss'
    ],
  },

Now, let's update our button component with our mixin:

<!-- src/components/button/button.vue -->
<template>
    <button
        class="app-button"
    >
      <slot></slot>
    </button>
</template>

<style lang="scss">
  .app-button {
    position: relative;
    display: inline-flex;
    cursor: pointer;
    white-space: nowrap;
    vertical-align: top;
    text-decoration: none;
    outline: none;
    @include center-item;

    // variant
    &--primary {
        background-color: $primary;
        color: $white;
    }
}
</style>

Functions

Functions in SASS are used to write complex operations or behaviours that can be reused in other parts of the code.

Let's create a function to handle a media query for our application.

// assets/style/functions.scss

// Get the difference between 2 numbers.
@function minus($param1, $param2) {
  @return $param1 - $param2;
}

// Get the sum of 2 numbers.
@function add($param1, $param2) {
  @return $param1 + $param2;
}

This is a basic example of what a function can be used for. More complex cases, like calculating percentage, can also be done.

Let's import our mixin in Nuxt config:

 styleResources: {
    scss: [
      '~/assets/style/variables.scss',
      '~/assets/style/mixins.scss',
      '~/assets/style/functions.scss'
    ],
 },

Let's update our button component with our function:

<!-- src/components/button/button.vue -->
<template>
    <button
        class="app-button"
    >
      <slot></slot>
    </button>
</template>

<style lang="scss">
  .app-button {
    position: relative;
    display: inline-flex;
    cursor: pointer;
    white-space: nowrap;
    vertical-align: top;
    text-decoration: none;
    outline: none;
    @include center-item;
    width: minus(30px, 100%);

    // variant
    &--primary {
        background-color: $primary;
        color: $white;
    }
}
</style>

We have been able to add SASS to our Nuxt project, and also looked at some ways in which SASS can make our codebase look cleaner.

I hope this article has been helpful to you. If you encounter any issues, you can reach out to me on Twitter or Github.

About the author

Adesoji Temitope

Adesoji Temitope

Software Engineer

Keep reading

View all posts →

I Broke My Hand So You Don't Have To (First-Hand Accessibility Insights)

A perspective of a temporarily impaired developer on accessibility both from the perspective of a user and of a software engineer. Using the web disabled “surprisingly” makes you think about people’s experience on the web. Let us take you on that journey!...

Jan Kaiser5 mins
AccessibilityA11yWeb DevelopmentHTML

Nuxt DevTools v1.0: Redefining the Developer Experience Beyond Conventional Tools

Nuxt DevTools v1.0 is a game-changer for web developers, featuring integrated VS Code, real-time views, and a customizable UI. This new toolset enhances efficiency, revolutionizing web development....

Jesús Padrón8 mins
VueNuxtJSDevToolsJavaScript

Understanding Vue's Reactive Data

A blog post that unravel how Reactivity works in Vue 3...

Jesús Padrón7 mins
VueJavaScriptTypeScriptWeb Development

Nuxt 3 Demo App with Prerender and SSR

Introduction The quest for an optimal web application involves numerous factors, such as performance, user experience, and search engine optimization (SEO). Nuxt 3 provides excellent features out of the box that can help you tackle these aspects efficiently. This article will guide you in creating a Nuxt 3 application using Server Side Rendering (SSR) and pre rendering capabilities. We'll craft an application that offers a seamless user experience, superior performance, and improved SEO. Server Side Rendering in Nuxt 3 Enhancing User Experience and SEO with SSR In the world of web development, Server Side Rendering (SSR) has gained significant traction. It refers to the server rendering the webpage upon each request rather than the client. With SSR, your web page arrives fully formed at the client's doorstep, reducing the time for the first painting. The advantage of SSR extends beyond just performance and user experience. It's also a darling of search engine crawlers, which find it easier to index your website with fully formed page content at the time of their crawl. In simple terms, it's like providing a tour guide to lead the search engine around your website, ensuring they get all the spots! The Power of SSR in Nuxt 3 Nuxt 3 has built in support for SSR by default. It allows you to optimize your application by loading the data before rendering the page. To take advantage of SSR, you simply build your application as you usually would. In this case, using the fetch() method to load some. In this example, the fetchData function fetches the data before rendering the page. The data then gets displayed within the tag. Sidenote, if you wanted to disable SSR in your Nuxt application, you would do so in your nuxt.config.ts file: More details on how this works can be found in the rendering modes section in the official Nuxt 3 documentation. Pre rendering in Nuxt 3 Amplifying Application Performance with Pre rendering While SSR has its advantages, another superhero in our story is pre rendering. Pre rendering refers to the process of generating the static HTML pages of a site in advance. It's like preparing a feast before the guests arrive so you can serve them promptly. Like SSR, pre rendering enhances SEO, as search engines can index fully rendered pages. Especially for content heavy applications, pre rendering can give a turbo boost to performance, leading to better user engagement and retention. Leverage Pre rendering with Nuxt 3 Nuxt 3 supports SSR and Static Site Generation (SSG), including pre rendering. To enable prerendering, you need to export your routes in nuxt.config.ts: These routes will be pre rendered during the build phase, allowing for swift navigation. Let's update our application to pre render the users' list: In the nuxt.config.ts`, include the users' route for pre rendering: Going beyond with Nuxt 3 While SSR and pre rendering are significant for performance and SEO, Nuxt 3 offers more advanced features like hot module replacement, Vue 3 integration, improved error handling, and more. Nuxt 3 also has different kinds of rendering modes for different applications; in our SSR case, we used the default Universal rendering mode. Leveraging these features allows you to develop robust, high performance, and user friendly applications. Conclusion In this article, we delved into the concepts of SSR and pre rendering in Nuxt 3. We explored how these techniques contribute to enhancing performance, user experience, and SEO. You can create exceptional web applications by integrating Vue 3's capabilities with Nuxt 3's robust features. A well structured, performant, and SEO friendly application not only attract users but also retains them. Embrace the power of Nuxt 3 and Vue 3 in your development journey. Happy coding!...

Allan M. Jeremy3 mins
NuxtJS