Onjsdev

Share


How To Use SASS Variables In Vite Vue Components


By onjsdev

Jan 7th, 2024

When working on Vue applications constructed with Vite, it's necessary to import your SASS _variables file into the style tags of each component to use global styling variables in components.

However, this process is frustrating and time-consuming. In this article, we'll show you how to seamlessly use global SASS variables in the _variables.scss file in your Vue components, eliminating the need to import the variables file into each component.

Configuring Vite Config File

Before you import SASS variables into your Vue components, you need to set up SASS in your Vue project. Assuming you already have a Vue project created, follow these steps:

First, install the sass package

npm i sass

Then, configure your project to use SASS in your vite.config.js file. If the file doesn't exist, create it in the root of your project and add the following code:

import { fileURLToPath, URL } from "node:url";

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

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

In this example, we assume that your SASS variables are stored in a file named _variables.scss located inside the src/assets directory. Note that the @ symbol refers to the src folder, so make sure to write the correct path for the SASS variables.

Now, import your _variables.scss file into your main SASS file as usual.

// ./assets/main.scss

@import "variables.scss";

body {
  background-color: $color;
}

Then import this main.scss file into the Vue main.js file.

import "./assets/main.scss";

import { createApp } from "vue";
import App from "./App.vue";

createApp(App).mount("#app");

Now, you are ready to use global SASS variables in your vue components without importing them.

Here is the example

<template>
  <div>
    <h1>Hello World</h1>
  </div>
</template>

<style scoped lang="scss">
h1 {
  font-weight: 500;
  font-size: 2.6rem;
  position: relative;
  top: -10px;
  background: $color;
}
</style>

Conclusion

Using SASS variables in Vite Vue components without importing the _variables file into style tags make easy styling components. In this article we covered how to add global sass variables to each component without importing them.

If you want to learn more about SASS and Vuejs then you can check the following articles: