Enable seamless SCSS inclusion in Vue components through automatic importing

My goal is to import a variables.scss file globally in my Vue project. I have set up my vue.config.js file as follows:

module.exports = {
        css: {
            loaderOptions: {
                scss: {
                    additionalData: `@import "@/styles/variables.scss";`
                },
            }
        }
}

The contents of variables.scss are:

$dark-bg: #1C2537;

In the Vue file where I attempt to use these variables, the code snippet looks like this:

<script setup>
// Component logic
</script>

<template>
    <!-- Template -->
</template>

<style lang="scss">
@import '@/styles/variables.scss'; // When I add this line, everything works
.left-menu {
  background-color: $dark-bg;
}
</style>

When I directly import variables.scss in the Vue file, it works fine, but global import does not. Any insights into what might be causing this issue?

Here are the versions I am using: "sass": "^1.69.5", "sass-loader": "7.3.1", "vue": "^3.2.26"

I expect the variables from variables.scss to work globally across all Vue files.

Answer №1

If you want to include the file path of your scss file in your vue.config.js configuration, follow this example:

const config = {
  css: {
    loaderOptions: {
      scss: {
        additionalData: `@use "@/assets/scss/variables/variables.scss" as *;`
      },
    },
  },
};

Answer №2

My configuration is quite similar to yours, except for the scss property, which is set as `sass :

The syntax for sass-loader version 9 and above is:

    loaderOptions: {
      sass: {
        additionalData: `
          @use "sass:math";
          @import "@/css/_colors.scss";
          @import "@/css/_animations.scss";
          @import "@/css/_mixins.scss";
        `
      }
    }

In my .vue file, I am able to use the following without any errors:

<style lang="scss">
  .message {
    color: $error-color;
  }
</style>

According to the documentation, sass options are also applicable to scss options, so you might want to give it a try.

In my package.json, I have declared the versions of vue / sass and sass-loader as follows:

    "vue": "^3.2.47",
    "sass": "^1.51.0",
    "sass-loader": "^12.6.0"

An important note in the documentation: in sass-loader version 8, this option is named as prependData.

EDIT After further investigation due to differences in sass-loader versions, it seems that you should use the data option, as recommended by Alex in the comments.

Refer to the changelog for version 8 where they mention that

the data option was renamed to the prependData option

Then, check the changelog for version 9 where they state that

the prependData option was removed in favor of the additionalData option, as documented

So here is the correct syntax for sass-loader version 8 (compatible with scss or sass loaderOptions):

    loaderOptions: {
      scss: {
        prependData: `@/styles/variables.scss";`
      }
    }

For version 7 and below:

    loaderOptions: {
      scss: {
        data: `@/styles/variables.scss";`
      }
    }

And for version 9 and above:

    loaderOptions: {
      scss: {
        additionalData: `@/styles/variables.scss";`
      }
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps can I take to modify the class of a button once it has been clicked using JQuery?

Currently, I am experimenting with Jquery to dynamically change the classes of bootstrap buttons when they are clicked. However, I have encountered a limitation while using toggleClass. The issue is that I am only able to toggle between two classes, whic ...

What is the best way to populate missing days in an array up to the current date that do not already contain the "Present" element?

Consider the array below which contains attendance data for an employee (Retrieved from Mongo using Ajax): [{"_id":"5fcdcd49c3657d1e05b846f5","title":"Present","allDay":true,"start":"2020-11- ...

Using JavaScript to create a tree structure with hierarchical organization in JSON

Having some trouble converting a nested hierarchical tree from a JSON array. Looking to create a hierarchical tree structure from the provided JSON data. Below is the data: [{ "_id" : "59b65ee33af7a11a3e3486c2", "C_TITLE" : "Sweet and Snacks", ...

Explore the feature of toggling visibility of components in Vue.js 3

I am facing an issue with showing/hiding my sidebar using a button in the navbar component. I have a navbar and a side bar as two separate components. Unfortunately, none of the methods I tried such as v-show, v-if, or using a localStorage value seem to wo ...

Symfony allows for the addition of an embedded collection prototype with an empty string

It seems like I must be overlooking something simple. I'm currently referencing this guide http://symfony.com/doc/current/cookbook/form/form_collections.html and aiming to include a link/button for adding more filters to a brand. However, the data-pr ...

How to use getBoundingClientRect in React Odometer with React Visibility Sensor?

I need help troubleshooting an error I'm encountering while trying to implement react-odometer js with react-visibility-sensor in next js. Can anyone provide guidance on how to resolve this issue? Here is the code snippet causing the problem: https:/ ...

Expanding a collection of text inputs on-the-fly (HTML/JavaScript)

Looking to streamline our data entry process, I am developing an app for in-house tasks. Our team will be required to input information about various "items" that correspond to multiple "categories." To facilitate this task efficiently, I'm explorin ...

When Chrome DevTools are opened, some elements of a webpage undergo a transformation in their style

I've recently started working on a static webpage using VueJS/NuxtJS and Buefy as the UI library, although I am still learning about these technologies. One issue that I have encountered is that certain elements on the page change style when I open C ...

What is the best way to retrieve the js window object within emscripten's EM_JS function?

I'm looking to access the window.location in an EM_JS method in order to call a JavaScript method from C++. My attempted approach was: EM_JS(const char*, getlocation, (), { let location = window.location; let length = lengthBytesUTF8(location ...

Having trouble with the post method being not allowed in your SPA Vue on Laravel application? Have you tried

This question has been raised multiple times, with varying solutions that have not proven to be effective. Despite my attempts to set the csrf-token in different ways, I still can't get it to work. My goal is to create a Single Page Application (SPA) ...

Managing responses from ajax requests that can handle both text and json formats

After submitting a form via Ajax and receiving a response from the servlet in either text or JSON format, I'm wondering if there is a way to handle both types of responses. I've read through the jQuery/Ajax documentation, but the JQuery Ajax page ...

JavaScript: Obtaining a Distinct Identifier for Various Replicated Entries

Imagine we have an object: var db = [ {Id: "201" , Player: "Jon",price: "3.99", loc: "NJ" }, {Id: "202", Player: "Sam",price: "4.22", loc: "PA" }, {Id: "203" ,Player: "Sam",price: "4.22", loc: "NY" }, {Id: "204", Player: ...

Implementing jQuery functionality on elements that are generated dynamically

I'm facing a challenge when working with dynamic elements in jQuery and I really could use some help. Let me provide an example from my current project: main.js $(function () { renderPlaceList(places); setupVoting(); } The two functions are ...

Steer clear of using inline styling when designing with Mui V5

I firmly believe that separating styling from code enhances the clarity and cleanliness of the code. Personally, I have always viewed using inline styling (style={{}}) as a bad practice. In Mui V4, it was simple - I would create a styles file and import i ...

The URL overwrites the Ajax transfer type

When making an ajax call using a generated URL from a paginator script, I encountered an issue. The URL was dynamically created as shown below: "http://192.168.1.23:8000/pricing/0/999/null/?page=9" A similar link is generated on the server: "https://xxx ...

Submitting content to numerous webpages

I'm looking to submit form data on multiple pages, while keeping the main action as "". After clicking, I want the page to refresh but also send the POST data to another .php file. This is necessary because the other .php file generates a graph that ...

sending a transformed javascript array from php to a javascript function

I'm looking for a way to pass a JavaScript array (that has been converted from PHP to JS) from PHP code to a JavaScript function. <?php // Convert PHP array to JavaScript array $php_array = array('he','hi','hello'); ...

Troubleshooting Vue/Vuetify: Inability to use the Esc key to show/hide dialog in parent component

I have been utilizing the vuetify library in my project. I encountered an issue where the ESC key does not work when opening a dialog from a child component to a parent component for the first time. It seems like there might be a mistake in my implementati ...

Using JSON to insert an array into an object with identical key name

var arr = ['1', '2', '3'] var part = {} var partContents = [] arr.map(function(i){ partContents.push({ obj: i }) part['text'] = partContents }) console.log(part); Is there a way to create separate arrays with ...

Having trouble loading the React app when using the @mui/styles package

After downloading a package from the MUI website, I encountered an error when trying to import "@mui/styles" which is resulting in browser errors. The package was downloaded from this source: https://mui.com/system/styles/basics/ Upon running my React app ...