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

Guide on sending files through an API request with formData() using Vuejs and Axios

My goal is to utilize an API to upload a file to the server. The documentation on documenter.getpostman outlines how to use the API: --form 'type="1"' \ --form 'user_id="1"' \ --form 'file=@"/C:/U ...

Using the methods res.render() and res.redirect() in Express.js

I'm facing a challenge with a route in my express app, where I need to achieve the following: Retrieve data from an external source (successful) Show an HTML page with socket.io listening for messages (successful) Conduct lengthy calculations Send a ...

Azure Chatbot that logs conversations in Webchat whenever the user selects 'none of the above' option

Recently, I've delved into the world of web chat services and embarked on a journey to craft a chat bot using pure JavaScript code that can seamlessly integrate into any HTML file. Despite consulting Microsoft's documentation, I find myself in a ...

Issue with ng-checked not detecting boolean values retrieved from local storage

I'm working on a code snippet in my controller where I have a checkbox in my HTML with "ng-checked="enterToSend" and "ng-click="enterToSendCheck()" attached to it. $scope.enterToSend = localStorage.getItem('enterToSend'); $scope.enterToSen ...

Best practices for passing multiple values with keys in vue.js when constructing URLs

I am working with this data containing various attributes: for(var k = 0;k<this.form.fields.length;k++) { this.dynamic_fields.push({attribute_id:attributes[k].id,value: attributes[k].value}) ...

Implement a JavaScript confirm dialog for a mailto hyperlink

Is there a way in javascript to automatically detect mailto links on the page and prompt a confirmation dialog when clicked by a user? I came across a method on this website for displaying an alert message. My knowledge of javascript is very basic. It&ap ...

Can you please provide the appropriate PropTypes for a dictionary in a ReactJS project?

Looking for something along the lines of y = {"key0": [value0, value1], "key1":[value2]} What is the proper way to define the proptypes for y? ...

The Safari keyboard navigation feature suddenly disappeared after uploading to Google App Engine

My current website is built using Vue.js (2.x) and deployed on Google App Engine. After testing the deployed application in Safari, I noticed that the accessibility feature "'skip navigation' on :focus" was no longer functioning proper ...

How can I access an array option that combines both global and target-specific specifications within a grunt plugin?

Currently, I am in the process of creating a grunt plugin that includes options which can consist of arrays of values. These values are specifically file paths (distinct from the files listed in the task's own 'files' property). The setup fo ...

Guide to implementing optional localization strings in React-Router paths

Incorporating react-router, I aim to implement internationalization for links following this format: domain.com/langISO/countryISO2/page Here are some examples of valid routes: domain.com/ -> Home Page domain.com/en/us -> Home Page domain.com/fr/f ...

Designing a user interface that consists of numerous distinct components

Challenge I'm faced with a dilemma regarding site A, which is built using React. Specifically, I need to find a way to integrate smaller React components into site A whenever a user navigates to a specific page within the site. Each of these smalle ...

The sequence for conducting operations within a function in JavaScript (Vue.js)

I am currently working on building a contact-list app using Vue.js. Each contact in the list can have multiple addresses, emails, and phone numbers. To accommodate this, I have set up inputs and a button to add additional fields as needed. My issue arises ...

Utilizing Vue.js 2.0 to Generate Multiple Bootstrap Modals

Trying something new can be challenging, especially when it comes to creating an image gallery in vue.js. As a beginner with this framework, I decided to use vue-bootstrap for my project. However, I ran into some confusion when trying to implement a modal ...

In NextJs version 13, you can access parameters from the URL directly within the layout.js file

With the introduction of server components in Next.js 13, accessing parameters from the URL has become seamless. Let's look at an example: app/shop/[tag]/[item]/layout.js /shop/1/2 { tag: '1', item: '2' } When accessing page ...

Rearranging anchor tag order with the power of JQuery

Imagine I have five anchor tags <a id = "A" class = "Home">Home</a> <a id = "B" class = "Maps">Maps</a> <a id = "C" class = "Plans">Plans</a> <a id = "D" class = "Community">Community</a> <a id = "E" clas ...

What is the best way to incorporate custom KnockoutJS functions using RequireJS?

I am facing an issue with my View Model that utilizes a custom observableArray function for sorting. The error message I receive states: "...has no methods 'sortByProperty'". How do I go about loading the handlers.js file to resolve this problem ...

reCAPTCHA v3 - Alert: There are no existing reCAPTCHA clients available

After coming across a similar issue on Stack Overflow (link to the question here), I attempted to implement reCAPTCHA on my website to combat spam emails received through the form. Despite following Google's instructions, I encountered an error that p ...

Accessing an object within an array in a Node.js EJS file

Great job everyone! I've developed a project using Node.js which includes the following schema structure: const debt = new Schema({ name: { type: String, required: true, }, medicine: [{ data: { type: Schema.Types.ObjectId, ...

What is the best way to display a variable from a function located outside of the public http folder in PHP?

I am attempting to create a registration form using Ajax. I have a script that calls a registration function located in an includes folder outside of the public html folder. The output of this function should be alerted, but when I click the button, the al ...

Using node.js for synchronous callbacks in node.js programming

I am new to node.js, and from what I've gathered, each callback creates a new event that can be executed in parallel. For instance, consider the following code with a callback: function testFunction(var1){ s3.head(var1, function(data, err){ ...