Home > Software engineering >  Sass global variables and mixins not working
Sass global variables and mixins not working

Time:05-23

I've set up a project using Vue 3.2.33 and Vite 2.9.5

When I try to access any global variable or mixin from within any vue component, I get an undefined error. This problem doesn't occur in scss files.

The import itself seems working correctly because any css rules in it are working.

vite.config.ts:

import { fileURLToPath, URL } from 'url';

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [vue()],
    resolve: {
        alias: {
            '@': fileURLToPath(new URL('./src', import.meta.url)),
        },
    },
    css: {
        preprocessorOptions: {
            scss: {
                additionalData: '@use "@/styles/variables";',
            },
        },
    },
});

src/styles/_variables.scss:

// breakpoints
$breakpoints: (
    "sm": 576px,
    "md": 768px,
    "lg": 992px,
    "xl": 1200px,
    "xxl": 1400px,
);

@mixin test {
    border: 3px solid red;
}

Example use:

<style scoped lang="scss">
@use 'sass:map';

.container {
    max-width: 100%;
    width: 100%;
    margin: 0 auto;
    @include test; // <- undefined

    &--fluid {
        max-width: 100%;
        width: 100%;
    }
}

$widths: (
    'sm': 540px,
    'md': 720px,
    'lg': 960px,
    'xl': 1140px,
    'xxl': 1320px,
);

@each $breakpoint, $width in $widths {
    @media (min-width: map.get($breakpoints, $breakpoint)) { // <- $breakpoints undefined
        .container {
            max-width: $width;
        }
    }
}
</style>

CodePudding user response:

I've managed to "fix" the issue. Turns out, when I replace all @use rules for file imports, the sass code is imported correctly and works. But this produces a new problem as the @import rules cannot be placed before @use, so I had to remove the additionalData key from config and include the imports manually.

  • Related