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!