Global Sass Import & Usage - Nuxt 3 Static Assets

Viewed 6695

I am trying to import a global Sass stylesheet from the /assets directory and use stuff like variables and mixins defined there throughout the components. My nuxt.config.ts looks like this currently:

import { defineNuxtConfig } from "nuxt3";

export default defineNuxtConfig({
    css: ["@/assets/styles/main.sass"],
    styleResources: {
        sass: ["@/assets/styles/main.sass"],
    },
    build: {
        extractCSS: true,
        styleResources: {
            sass: "@/assets/styles/main.sass",
            hoistUseStatements: true,
        },
    },
    // buildModules: ["@nuxtjs/style-resources"], // This throws error
    vite: {
        css: {
            loaderOptions: {
                sass: {
                    additionalData: ` @import "@/assets/styles/main.sass"; `,
                },
            },
        },
    },
});

When I try to use a variable now, I get [plugin:vite:css] Undefined variable. error. This used to work very well in Nuxt 2 with @nuxtjs/style-resources but I'm not sure how to make this work in Nuxt 3.

However, classes and applied styles from that stylesheet are working, only varibles, mixins and maps are not accessible.

Can someone please help?

2 Answers

Okay, so this solution worked after playing around for a while

import { defineNuxtConfig } from "nuxt3";

export default defineNuxtConfig({
    css: ["@/assets/styles/main.sass"],
    vite: {
        css: {
            preprocessorOptions: {
                sass: {
                    additionalData: '@import "@/assets/styles/_variables.sass"',
                },
            },
        },
    },
});

Here,

  • main.sass contains the classes and styles
  • _variables.sass contains the mixins, variables, maps, etc

Note that in _variables.sass, you need to have an empty line at the beginning of the file to avoid error. It's a problem we're facing at the moment, hopefully will be solved soon.

I guess I need more reputation to comment, but is this working for others? I'm getting an error that reads:

[plugin:vite:css] expected newline.
  ╷
1 │ @import "@/assets/styles/_variables.sass"$foo: green
  │                                          ^
  ╵
  assets/styles/main.sass 1:42  root stylesheet
Related