Unable to transfer Sass variables to JavaScript

In my Vue project, I am attempting to export SASS variables into Javascript by using the following code snippet:

_export.sass

:export
    colorvariable: blue
    othercolorvariable: red

I found inspiration from a post on Stack Overflow for this approach. However, when I try to import my sass file as shown below...

About.vue

<script>
import styles from "@/styles/_export.sass";

export default {
    name: "About",
    data() {
        return { styles };
    }
};
</script>

I encounter the following error:

WAIT  Compiling...                                                                                                 2:17:03 AM

98% after emitting CopyPlugin

 ERROR  Failed to compile with 1 errors                                                                             2:17:03 AM

 error  in ./src/styles/_export.sass

Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Invalid CSS after '...les/main.sass";': expected 1 selector or at-rule, was "export: {"
        on line 1 of /Users/MatthewBell/GitHub/pollify/client/src/styles/_export.sass
>> @import "@/styles/main.sass";

   -----------------------------^


 @ ./src/styles/_export.sass 4:14-227 14:3-18:5 15:22-235
 @ ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/views/About.vue?vue&type=script&lang=js&
 @ ./src/views/About.vue?vue&type=script&lang=js&
 @ ./src/views/About.vue
 @ ./src/router/index.js
 @ ./src/main.js
 @ multi (webpack)-dev-server/client?http://192.168.2.37:8080/sockjs-node (webpack)/hot/dev-server.js ./src/main.js

If I exclude

import styles from "@/styles/_export.sass";
, the code compiles without any issues.

After researching this error, I came across a related post that suggests my Vue configuration file might not be set up correctly. Here is my vue.config.js:

module.exports = {
    css: {
        loaderOptions: {
            sass: {
                prependData: `@import "@/styles/main.sass"`
            }
        }
    }
};

It is important to note that the main.sass file mentioned above does not import _export.sass. However, everything was functioning correctly until I attempted to import _export.sass into my Javascript file.

My goal is to successfully import the variables from _export.sass into my JS script, similar to the code snippet above. How can I accomplish this?

Answer №1

Regrettably, the SASS/SCSS documentation does not provide any information about the export feature. Therefore, unless you want to rely on trial and error, the recommended approach would be to switch to SCSS and use the commonly practiced solution (despite the lack of documentation).

Personally, I prefer to import my SCSS variables and then export them to JS. In my _export.scss file, I structure it like this:

@import "variables";

:export {

    // Exporting the color palette for accessibility in JS
    some-light-blue: $some-light-blue;
    battleship-grey: $battleship-grey;
    // and so on...

}

NOTE: It is crucial to only use _export.scss in JS files and avoid importing it into SCSS files. Importing _export.scss in your SCSS files will lead to unnecessary style exports in your CSS and duplicate style exports in every compiled SCSS file.

Answer №2

If you're looking to enhance your Vue SFC styles block, utilizing CSS Modules is a fantastic option. An example of how this can be implemented is shown below:

<template>
  <button :class="$style.button" />
</template>

<style module>
  .button {
    color: red
  }
</style>

It's important to note that while some may refer to Sass, it's often more appropriate to use the .scss file type, as it offers a more modern syntax compared to the older .sass. However, the choice between the two ultimately comes down to personal preference.

Answer №3

styles.scss

$main-color: #1abbd5; //Blue

:export {
  pageColor: $main-color;
}

index.js

import styles from '../styles.scss'

To utilize this, simply do:

styles.locals.pageColor

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

How can I display the Bootstrap 5.3.0 Collapsible button on this basic website?

I've been struggling to implement a Bootstrap Collapsible on my web page using Bootstrap version 5.3.0. I've tried different approaches but I can't seem to get it to work. All I need is a Collapsible that contains a few links, which should b ...

Preventing multiple tabs in a form with PHP

I have successfully used JavaScript to prevent a link from being opened in multiple browser tabs every time a user clicks on it. For example, if the destination of my link is Google, it will create a new tab if one does not already exist but refresh the ex ...

Logging into Twitch API using asynchronous functions and VueJS

Hey there, I'm currently utilizing Nuxt to develop an application that integrates with Twitch. One of my main goals is to allow users to easily sign in using their Twitch credentials. I have already set up the necessary components within Twitch and o ...

Remove the background color from a semi-transparent circular CSS div when it is being dragged

My circular div is being dragged for a drag and drop operation, but there's always a translucent square around it. How can I remove this unwanted effect? body{ background : #BBD1DF; } .dragdemo { width: 170px; height: 170px; line-hei ...

What is the process for obtaining a value when you click and then retrieving the associated ID?

I am looking to create a function that, when clicking on the square with the ID "colors", will return the sentence containing the colors from the table in PHP files with the ID "retours_couleurs". Apologies for any mistakes in my English, as I am French. ...

Module fails to load in the proper sequence

As a .NET developer who is relatively new to modern client-side web applications, I am currently working on developing an Angular2 charting application using Chart.js. The modules are being loaded with SystemJS. Below is the content of my systemjs.config. ...

JQuery transmits null values

I have been troubleshooting my code for what feels like forever, but I just can't seem to find the error... My current project involves experimenting with JQuery and AJAX. I created a simple form with a textarea for submission. The form works perfect ...

Tips for effectively utilizing Mongoose models within Next.js

Currently, I am in the process of developing a Next.js application using TypeScript and MongoDB/Mongoose. Lately, I encountered an issue related to Mongoose models where they were attempting to overwrite the Model every time it was utilized. Here is the c ...

Displaying Mustache.js in an HTML template

I attempted to integrate mustache.js into my web application. After loading the mustache.js file, I included the following script in my code: <script type="text/javascript> $(document).ready(function () { var person = { first ...

The ajax request functions smoothly on the OS X Paw app and cURL, but does not work properly when coded in Javascript / jQuery

Currently delving into the world of ajax requests, I've been utilizing the Paw app to troubleshoot one. Surprisingly, the request functions flawlessly within Paw itself and even the cURL code generated by Paw works like a charm. However, the JavaScrip ...

What's the best way to conceal the navbar while attempting to print the page?

Currently, I am working on developing an application for my school project. One of the features is an invoice sheet with a print option. However, when I try to print by clicking the button or using ctrl+p, the navbar appears in a chaotic and disorganized m ...

I'm having trouble modifying the backdrop to 'true' or removing it after setting it to 'static' in Bootstrap. Can anyone help me troubleshoot this issue?

I have been encountering an issue with changing the backdrop setting from 'static' to 'true' in Bootstrap modal. Here is the code I am using: $('#modal').modal({backdrop: 'static', keyboard: false, show: true}); ...

Tips for incorporating an outside model into vue.js with babylon js

Struggling with importing a gltf file into vue.js using babylon.js to create a 3D view on a webpage. The documentation online isn't very clear, and I've tried the following steps in my Hello.vue file: <div> <h1> Hello </h1> < ...

What kind of interference occurs between the sibling components when a div with ng-if is present in Angular?

I've been troubleshooting for hours to figure out why the Angular elements in one div suddenly stopped working. After some investigation, I realized that a sibling div with an ng-if="someVar" was causing the issue. Currently, when someVar is true, the ...

Searching for columns should be at the top of an angular datatable, not at the bottom

In my Angular 7 project, I am utilizing the library found at this link. I have followed the example provided, which can be seen here. Everything is working perfectly, except for the position of the search columns. I would like the search columns to appear ...

Testing the Limits of CSS Hover

I'm having trouble figuring out how to implement this. When hovering, a yellow square/background should appear with an offset similar to the one in the image below. I am utilizing bootstrap for this project. Any assistance or guidance would be greatl ...

Unable to access npm run build on localhost

I have developed a web application using react and node.js, and now I want to test it with a production build. After running npm run build in the app directory, I successfully created a build folder. However, when trying to run the application using local ...

Tips for concealing XHR Requests within a react-based single page application

Is there a way to hide the endpoint visible in Chrome's devtools under the network tab when data is fetched in React? Can server-side rendering solve this issue? ...

Generate a dynamic file import loop within a React application

Suppose I have a directory containing several .md files: /static/blog/ example_title.md another_example.md three_examples.md and an array that includes all the titles: const blogEntries = ["example_title", "another_example", "three_examples"] In ...

Converting JSON data from a PHP variable into a jQuery array: What you need to know

I attempted to retrieve addresses using the postcode and applied the getaddress.io site API with PHP. This resulted in a JSON dataset stored in the PHP variable $file. Now, I am tasked with converting this JSON result into a jQuery array. { "Latitude":-0. ...