Globale Sass-Variablen und Mixins funktionieren nicht
P粉722521204
P粉722521204 2024-03-19 16:04:11
0
2
371

Ich habe ein Projekt mit Vue 3.2.33 und Vite 2.9.5 eingerichtet

Ich erhalte die Fehlermeldung „Undefiniert“, wenn ich versuche, von einer Vue-Komponente aus auf eine globale Variable oder ein Mixin zuzugreifen. Dieses Problem tritt bei SCSS-Dateien nicht auf.

Der Import selbst scheint gut zu funktionieren, da alle darin enthaltenen CSS-Regeln gültig sind.

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

Anwendungsbeispiel:

<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

Antworte allen(2)
P粉205475538

使用

@import

在你的 vite 配置中而不是

@use

vite.config.ts

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

请记住,您不能在 main.ts 文件中再次导入相同的文件 variables.scss,否则,您将收到此错误

[sass] This file is already being loaded.

顺便说一句,您也可以按照您提到的方式在每个组件中手动导入 scss 文件,但这确实很乏味,因此在 preprocessorOptions 中使用全局导入对于像 variables.scss 文件这样全局使用的文件来说,vite.config.ts 是一个更好的选择。

P粉938936304

我已经设法“解决”了这个问题。事实证明,当我替换文件导入的所有 @use 规则时,sass 代码已正确导入并可以工作。但这会产生一个新问题,因为 @import 规则不能放在 @use 之前,因此我必须从配置中删除 additionalData 键并手动包含导入。

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!