How to use global SASS variables in my Nuxt 3 components

Viewed 3209

Nuxt 3 first Release Candidate will be launched very soon, so I am starting a fresh new project with Nuxt 3. I am already facing an usual issue, and I was about to ask how to solve it. But I managed to do it by myself, so I am making a Self Answered question, in order to help people that might face the same issue in the futur.

How to use global Sass (or Scss) variables in my vue components ? I saw on other posts that we can use the @nuxtjs/style-resources package, but it seems like a Nuxt 2 package. And I think there might be a better way to do it in Nuxt 3 without adding dependencies like style-resources ?

What I mean by "global variable" is a SASS variable is that I want to be able to use the SASS variable in any of my Vue components, without having to include SASS files.

What I want

(Given that I already installed the sass package)

// @/assets/style/main.sass
$grey-bg: #CCC
$light-blue: #c6d8f5
<!-- app.vue -->
<template>
  <div>
    <NuxtWelcome />
  </div>
</template>

<style lang="sass">
body
  background-color: $grey-bg
  color: $light-blue
</style>

What I already tried

I tried to include my sass file in the Nuxt config CSS property like this :

// nuxt.config.ts
import { defineNuxtConfig } from "nuxt3"

export default defineNuxtConfig({
    css: ["@/assets/style/global.sass"]
})

And it work in the way that the style in my global.sass file will be applied in my entire application. But it does not work in the way that if I refer to a variable in my SASS file from a Vue Component, the build fails with this error :

Plugin: vite:css. Error: Undefined variable.

1 Answers

In Nuxt 3, Vite will come out of the box, wich was not the case in Nuxt 2. Since Nuxt 3 then, we can put the vite config by default in the nuxt.config.ts file (refering to the documentation).

Wich means we can simply add a Vite preprocessorOptions additionalData property in the nuxt config :

// nuxt.config.ts
import { defineNuxtConfig } from "nuxt3"

export default defineNuxtConfig({
    vite: {
        css: {
            preprocessorOptions: {
                sass: {
                    additionalData: '@import "@/assets/style/global.sass"',
                },
            },
        },
    },
})

And I can also split my global SASS in different files. All the variables declared in any of those files will be available in all my components :

  • @/assets/style/global.sass
  • @/assets/style/_animations.sass
  • @/assets/style/_colors.sass
  • @/assets/style/_fonts.sass
// global.sass
@import "animations", "colors", "fonts"

Remember, we need to have the sass package install for that to work. If it is not already installed, run one of the following command :

yarn add -D sass
# or
npm install -D sass
Related