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>
use
in your vite config instead of
vite.config.ts
:Remember that you cannot import the same file
variables.scss
again in themain.ts
file, otherwise you will get this errorBTW you can also manually import the
scss
file in each component as you mentioned but that is really tedious so use global inpreprocessorOptions
Import For files that are used globally likevariables.scss
files,vite.config.ts
is a better choice.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 theadditionalData
key from the configuration and include the import manually .