Sass global variables and mixins not working
P粉722521204
P粉722521204 2024-03-19 16:04:11
0
2
413

I have set up a project using Vue 3.2.33 and Vite 2.9.5

I get undefined error when I try to access any global variable or mixin from any vue component. This problem does not occur in scss files.

The import itself appears to be working fine, as any css rules within it are valid.

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;
}

Usage example:

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

P粉722521204
P粉722521204

reply all(2)
P粉205475538

use

@import

in your vite config instead of

@use

vite.config.ts

export default defineConfig({
    plugins: [vue()],
    css: {
        preprocessorOptions: {
            scss: {
                additionalData: '@import "./src/styles/variables.scss";',
            },
        },
    },
});

Remember that you cannot import the same file variables.scss again in the main.ts file, otherwise you will get this error

[sass] This file is already being loaded.

BTW you can also manually import the scss file in each component as you mentioned but that is really tedious so use global in preprocessorOptions Import For files that are used globally like variables.scss files, vite.config.ts is a better choice.

P粉938936304

I have managed to "solve" this problem. It turns out that when I replaced all the @use rules that the file imported, the sass code was imported correctly and worked. But this creates a new problem because the @import rule cannot be placed before the @use, so I have to remove the additionalData key from the configuration and include the import manually .

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template