Pass SASS/SCSS variables to Javascript without the need to export them to CSS files

Context

Let's take a look at the _variables.scss file below:

/* Setting up color variables */
$white:    #fff;
$black:    #000;
$grey:     #ccc;
// and so on...

// Export the color palette for Javascript accessibility
:export {
    white: $white;
    black: $black;
    grey: $grey;
    // and so forth...
}

The main objective of this code snippet is to make the SCSS variables accessible in Javascript through importing like this:

import variables from 'variables.scss';

For a more in-depth explanation, you can refer to this link.

The Issue

Now, let's examine the following template example (using Vue.js but applicable to other frameworks as well):

<!-- Your template goes here... -->

<style lang="scss" scoped>

    // Importing Partials
    @import "~core-styles/brand/_variables.scss";
    @import "~core-styles/brand/_mixins.scss";

    // Your styles here...

</style>

In the example above, I've included the scoped attribute to highlight the potential problem, but even without scoped, the issue remains relevant.

Upon compilation, the above SCSS code will result in something like:

[data-v-9a6487c0]:export {
    white: #fff;
    black: #000;
    grey: #ccc;
    // and so on...
}

Furthermore, with the scoped attribute, this repetition will occur every single time _variables.scss is imported into a template, potentially leading to unnecessary code duplication. In larger applications with numerous components and a vast color palette, this could add thousands of lines of redundant code.

The Query

Is there a method to export SCSS variables to Javascript without exporting them to CSS?

Potential (Unconventional) Solution

I'm seeking an alternative to creating a separate file like _export.scss solely to export SCSS variables to JS, while excluding it from CSS builds...

To elaborate on the aforementioned workaround, here is what I currently implement (in a standard website scenario, this has saved me about 600 lines of unnecessary CSS code):

_export.scss

/*
 |--------------------------------------------------------------------------
 | SASS Export
 |--------------------------------------------------------------------------
 |
 | Include any variables to be exported to Javascript. This file
 | is omitted from CSS builds to avoid exporting the variables to CSS.
 |
 */

@import "variables";

:export {

    // Exporting the color palette for JS accessibility
    white: #fff;
    black: #000;
    grey: #ccc;
    // and so forth...

}

Instead of importing from _variables.scss, I import from _export.scss in my Javascript like this:

import styles from 'core-styles/brand/_export.scss';

By eliminating the export statement from the _variables.scss file, we can prevent the compiled CSS export code.

Note: The _export.scss file must be excluded from SCSS compilation!

Answer №1

Important: This answer is provided as I couldn't find a more optimal solution. If a better approach is suggested later on, I am open to accepting it.

It appears that the most effective way to tackle this issue is by moving the export statement from the _variables.scss file to its separate _export.scss file that will not be included in the SCSS compilation.

Here's how you can structure it:

_variables.scss - included in SCSS compilation

/* Define various colors */
$white: #fff;
$black: #000;
$grey: #ccc;
// and so on...

_export.scss - not part of SCSS compilation

@import "variables";

:export {

    // Exporting the color palette for JS accessibility
    white: #fff;
    black: #000;
    grey: #ccc;
    // and so on...

}

Subsequently, your app.scss (or brand.scss) file will resemble the following (without the @include "export";):

@import "variables";
@import "mixins";
@import "core";
@import "animations";
// and more...

Finally, _export.scss is solely referenced in JavaScript as follows (take note that core-styles is a personal alias I utilized in my projects):

import styles from 'core-styles/brand/_export.scss';

Answer №2

I'm curious if the issue lies in opting for @import over @use.

It's worth noting that @import is considered outdated as it duplicates code, leading to multiple versions of the same content.

Answer №3

Transfer your SCSS variables to CSS variables (--ivory, --ebony etc) and proceed with:

window.getComputedStyle(document.body).getPropertyValue('--ivory')

The disadvantage is potentially cluttering the document with unnecessary CSS variables. The advantage is avoiding the need for complex export/import processes.

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

Can you explain the mechanics behind the animation of the upvote button on steemit.com?

Behold the upvote button of steemit.com: <span class="Icon chevron-up-circle" style="display: inline-block; width: 1.12rem; height: 1.12rem;"> <svg enable-background="new 0 0 33 33" version="1.1" viewBox="0 0 33 33" xml:space="preserve" xmlns=" ...

What is causing the error when using Interfaces and Observable together?

I created a ToDoApp and integrated Firebase into my project, but I am encountering an error. ERROR in src/app/todo-component/todo-component.component.ts(25,7): error TS2740: Type 'DocumentChangeAction<{}>[]' is missing the following proper ...

React - Exploring the depths of functional components

Picture this: a straightforward form that showcases several unique components with customized layouts. The custom components include: <UsernameInput />, <PasswordInput />, <DateTimePicker />, <FancyButton />, <Checkbox /> Th ...

The act of appending values to an array within a hash in Vue is not functioning as expected

I am currently working on implementing a feature that allows users to add multiple workers by clicking the "Add worker" button. However, I have encountered an issue where placing the workers array inside the management object prevents this feature from f ...

Updating by clicking with auto-prediction feature

I have implemented an autosuggestion feature to display results from a database table while typing in an HTML field, and I am looking to utilize JavaScript to post another value from the same row where the autosuggested values are stored. https://i.stack. ...

Error in AJAX POST: base64 string formatting issue

Struggling with making an AJAX POST successfully upload and retrieve a base64 string to/from my SQL database. Upon receiving the string from the database via AJAX, it appears to be the same base64 string, but with random line breaks that render it non-func ...

Encountered an issue retrieving audio during recording with Recorder.js

I've come across a scenario where I'm utilizing the Recorder.js Demo for recording audio. Interestingly, it works perfectly on Linux but encounters an issue when used on Windows. A pop-up alert stating "Error getting audio" shows up. Here's ...

Executing a "call function from a Facebook button within a Vue component" operation in Vue

I'm currently working on integrating the Facebook-Login button into a Vue component. Is there a way to call a function in the parent component using the custom attribute "onLogin" from the button? HTML <complogin :page="page" inline-template v-if ...

How can I create a semantic-ui dropdown with a dynamically generated header?

Here are the dropdown options: const options = [ { key: '1', text: 'Example 1', value: 'Example 1', type:'ABC' }, { key: '2', text: 'Example 2', value: 'Example 2', t ...

Meteor push/browserhistory fails to navigate or refresh to a different page

Currently, I am attempting to set it up so that when a user clicks on a profile, they are redirected to the profile page of the user they clicked on. Here is the code I am using: const self = this; browserHistory.push({ pathname: '/user ...

What is the reason the .clearfix class fails to properly clear a floated element?

Check out this post: Understanding clearfix The most helpful response indicates that the clearfix should be applied directly to the last floating element: To incorporate a clearfix, you simply need to include HTML code: <div class="clearfix"> ...

Can fetch be used to retrieve multiple sets of data at once?

Can fetch retrieve multiple data at once? In this scenario, I am fetching the value of 'inputDest' (email) and 'a' (name). My objective is to obtain both values and send them via email. const inputDest = document.querySelector('i ...

Utilize JSON text importing for template literals in Node.js

When it comes to my node js projects, I usually opt for using a text.json file and requiring it rather than hardcoding static text directly into my code. Here's an example: JSON file { "greet": "Hello world" } var text = require('./text.json ...

Missing data: Node JS fails to recognize req.body

I've looked through various posts and I'm feeling quite lost with this issue. When I run console.log(req), the output is as follows: ServerResponse { ... req: IncomingMessage { ... url: '/my-endpoint', method: &a ...

Dynamically insert the ng-if attribute into a directive

In my code, I have implemented a directive that adds an attribute to HTML elements: module1.directive('rhVisibleFor', function ($rootScope) { return{ priority: 10000, restrict: 'A', compi ...

Implementing child components rendering in a React application using TypeScript

Just a little background information: I am attempting to build a carousel with pagination using ReactJS. Here is the code snippet I currently have: interface HTMLCarouselT { children: Array<JSX.Element> size: number; } const HTMLCarousel = ({ch ...

Tips for expanding the width of an image when employing position:relative

Below is the code snippet: <table border="1" cellpadding="2" cellspacing="2" height="250"> <tbody> <tr> <td> <div style="background: url('path to image'); width: 300px; height: 250px; position: ...

Overflow of text arranged horizontally within a span element situated inside a div container

I am currently working on developing a ticketing system that involves using nested div elements to organize content. Each ticket is represented by a main div containing various other nested divs and media such as images. While the functionality of the sys ...

Having trouble with @Mui and modularized scss conflicting sporadically. Is there a way to reliably overwrite @mui default styling using scss modules?

Currently, I am enhancing an existing React app that utilizes @mui/material components. The SCSS modules are linked to my JavaScript components, and I import them along with the material components like this. // STYLE IMPORT import styles from "./logi ...

Failed to load TypeScript file or similar issue

Whenever I attempt to generate a TypeScript file from a partial view (MVC .NET) that is loaded through a rest call and then appended to a div element, I encounter an error in my console. The error message reads: Uncaught ReferenceError: xyz is not defined ...