Home / Blog / Globally Load SASS into Vue.js with Vite
Globally Load SASS into Vue.js with Vite

Globally Load SASS into Vue.js with Vite

Alex Jover Morales
Alex Jover Morales
Updated: December 30th 2024

When building modern web applications, CSS preprocessors like SASS, LESS, and PostCSS offer developers powerful tools to write clean, maintainable stylesheets. Among these, SASS (or SCSS) remains a favorite for its feature-rich syntax and ability to make CSS more dynamic and reusable. In this guide, we’ll show you how to globally load SASS into your Vue.js 3 applications powered by Vite. This setup will save you from the tedious task of importing variables, mixins, and functions repeatedly in each component.

What Is SASS and Why Use It?

SASS (Syntactically Awesome Stylesheets) is a CSS preprocessor that extends the language by introducing features like:

These features make it easier to write styles that are organized, reusable, and easier to maintain.

Here are few examples for some key features of SASS that developers love:

  1. Variables
    Define reusable values for colors, fonts, or any other constants:

    $primary-color: #42b983;
    body {
     background-color: $primary-color;
    }
  2. Nesting
    Write cleaner, more readable styles by nesting rules hierarchically:

    .container {
     .header {
       color: blue;
     }
    }
  3. Mixins and Functions
    Create reusable blocks of styling code:

    @mixin center {
     display: flex;
     justify-content: center;
     align-items: center;
    }
    .box {
     @include center;
    }
  4. Partials and Imports
    Split your styles into smaller files (partials) and import them:

    @import "variables";
    @import "mixins";

With these features, SASS simplifies managing complex styles in large projects.

Why Configure Global SASS in Vue.js?

In large-scale Vue projects, SASS is often used to organize styles into reusable chunks like variables, mixins, and functions. However, without a global setup, you’ll need to manually import these files in every Vue component where you need them:

<style lang="scss">
@import "@/scss/_variables.scss";
@import "@/scss/_mixins.scss";
</style>

This can become a repetitive and error-prone task. By globally loading SASS files, you can ensure that all your Vue.js components have access to shared styles without extra imports, leading to cleaner and more maintainable code.

Setting Up Your Vue.js 3 Project with Vite

If you don’t already have a Vue.js 3 project, getting started is quick and easy with Vite, a fast and modern build tool. Run the following commands to scaffold a new Vue project:

npm create vue@latest

You will be prompted to select options and features in your new Vue project:

✔ Project name: my-vue-app
✔ Add TypeScript? … No / Yes
✔ Add JSX Support? … No / Yes
✔ Add Vue Router for Single Page Application development? … No / Yes
✔ Add Pinia for state management? … No / Yes
✔ Add Vitest for Unit testing? … No / Yes
✔ Add an End-to-End Testing Solution? … No / Cypress / Nightwatch / Playwright
✔ Add ESLint for code quality? … No / Yes
✔ Add Prettier for code formatting? … No / Yes
✔ Add Vue DevTools 7 extension for debugging? … No / Yes

Scaffolding project in ./<your-project-name>...
Done.

Once your project is ready, get into the project's root directory and install npm dependencies:

cd my-vue-app
npm install

How to Use SASS in Vite and Vue.js

To style the application with SASS, you'll be glad to know that Vite comes with excellent built-in support for various CSS preprocessors, including SASS.

While many build tools require additional plugins to work with preprocessors, Vite takes a simpler approach. It automatically handles the processing of .scss and .sass files (along with other preprocessor formats like .less, .styl, and .stylus), without requiring any Vite-specific plugins.

Install SASS Preprocessor in Vite

Even though Vite has built-in support for popular preprocessors, you'll still need to install the SASS preprocessor itself. This is because Vite deliberately separates the core build tool from the specific preprocessor implementations, allowing you to install only what you need. For our project, we'll use the sass package, which is the modern implementation of SASS written in pure Dart and compiled to JavaScript.

# .scss and .sass
npm install -D sass # or sass-embedded

This separation of concerns is actually a thoughtful design choice by the Vite team – it keeps the core tool lean while giving developers the flexibility to choose and manage their preferred preprocessor versions independently. It also means you're not locked into specific preprocessor versions that might be bundled with the build tool.

Now that your project is set up, it’s time to configure global SASS.

Configuring Global SASS in Vite

To globally load SASS files in a Vite project, you can use the additionalData option provided in the css.preprocessorOptions property of vite.config.js. This option allows you to prepend SASS code or imports to every Vue component's <style> block.

Here’s how to set up global SASS files in Vue.js with Vite:

  1. Open or create the vite.config.js file in your project root.
  2. Add the following configuration:
// vite.config.js
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';

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

The @ symbol in the import path is an alias for the src directory, which is configured by default in Vite. Make sure your SASS files, such as _variables.scss and _mixins.scss, are located in a folder like src/scss.

Benefits of the additionalData Option

By using Vite's additionalData option, any SASS variables, mixins, or functions you define in the globally imported files become available in every component without requiring explicit imports.

Here’s an example of how this simplifies your workflow:

// src/scss/_variables.scss
$primary-color: #42b983;

// src/scss/_mixins.scss
@mixin center {
  display: flex;
  justify-content: center;
  align-items: center;
}
<template>
  <div class="box">Hello World</div>
</template>

<style lang="scss">
.box {
  background-color: $primary-color;
  @include center;
}
</style>

Notice how the $primary-color variable and center mixin are used directly without any manual imports. This keeps your components clean and focused on their purpose.

Things to Watch Out For

While global SASS setups are incredibly convenient, there are a few caveats to keep in mind:

  1. Avoid Including CSS Rules in Globals
    Files imported globally should only contain non-rendered SASS code, such as variables, mixins, and functions. For instance, if _variables.scss includes a CSS rule like .box { color: red; }, that rule will be duplicated in every component’s styles. This leads to bloated CSS and potential performance issues.

  2. Scoped Styles Still Apply
    Even with global SASS, Vue’s scoped styles remain isolated to individual components. Global SASS doesn’t interfere with the scoping mechanism.

Real-World Use Cases

By globally loading SASS, you can implement consistent design tokens like colors, spacing, and typography across your app. For example:

  • Centralize theme variables in a _theme.scss file:
    $primary-color: #42b983;
    $secondary-color: #35495e;
    $font-stack: 'Roboto', sans-serif;
  • Reuse layout utilities in _mixins.scss:
    @mixin flex-center {
    display: flex;
    justify-content: center;
    align-items: center;
    }
  • Enable responsive design with _breakpoints.scss:
    $breakpoint-sm: 576px;
    $breakpoint-md: 768px;
    @mixin media-query($size) {
    @media (max-width: $size) {
      @content;
    }
    }

With these tools at your disposal, you can create a highly reusable and maintainable SASS framework for your Vue app.

Vite 6 and the Modern SASS API

In Vite 5, the legacy API for Sass was used by default. However, with the release of Vite 5.4, support for the modern API was added, allowing developers to choose between the two.

Now, in Vite 6, the modern Sass API is used by default. This update brings improved performance and better support for the latest Sass features. If you prefer the legacy API, you can still use it by configuring css.preprocessorOptions.sass.api: 'legacy' or css.preprocessorOptions.scss.api: 'legacy'. However, be aware that legacy API support will be removed in Vite 7, so it's a good idea to migrate to the modern API soon.

For more details on migrating to the modern API, check out the JS API migration guide on the official Sass documentation.

Wrapping Up

Globally loading SASS in Vue.js 3 with Vite is a simple yet powerful technique to streamline your styling workflow. By leveraging the additionalData option in Vite, you can eliminate repetitive imports and focus on building great Vue components.

If you want to learn more about Vite's CSS handling or SASS syntax and features, check out the Rapid Development with Vite course for additional insights about Vite.

Enjoy a cleaner, faster, and more productive Vue.js development experience!

Related Courses

Start learning Vue.js for free

Alex Jover Morales
Alex Jover Morales
Passionate web developer. Author of Test Vue.js components with Jest on Leanpub. I co-organize Alicante Frontend. Interested in web performance, PWA, the human side of code and wellness. Cat lover, sports practitioner and good friend of his friends. His bike goes with him.

Comments

Latest Vue School Articles

Exploring the Vue.js Ecosystem: Tools and Libraries That Make Development Fun

Exploring the Vue.js Ecosystem: Tools and Libraries That Make Development Fun

Explore the fun side of Vue.js development with our guide to its ecosystem. Discover UI libraries like Vuetify, Quasar, and tools enhancing your workflow like Pinia and Vue Router. Perfect for making coding efficient.
Eleftheria Batsou
Eleftheria Batsou
The Human Side of Vue.js: How Learning Vue Changes Your Life as a Developer

The Human Side of Vue.js: How Learning Vue Changes Your Life as a Developer

Explore how learning Vue.js can transform your career and personal development. From career growth to community involvement, discover the human side of coding with Vue.
Eleftheria Batsou
Eleftheria Batsou

Our goal is to be the number one source of Vue.js knowledge for all skill levels. We offer the knowledge of our industry leaders through awesome video courses for a ridiculously low price.

More than 200.000 users have already joined us. You are welcome too!

Follow us on Social

© All rights reserved. Made with ❤️ by BitterBrains, Inc.