Is there a way to import variables from javascript to sass or vice versa?
sass-ffi should do the trick, but the opposite way (from JS to SASS/SCSS). It will define a function called ffi-require
, which allows you to require
.js files from SASS:
config.js
:
module.exports = {
maxColumns: 4,
};
style.scss
:
$max-columns: ffi-require('./config', 'maxColumns');
Works with sass-loader
(webpack) and node-sass
.
I consider my solution to be quite hokey; but it does work...
In my _base.scss
I have some variables defined:
$menu_bg: rgb(45, 45, 45);
$menu_hover: rgb(0, 0, 0);
In a menu.scss
I have:
@import "base";
#jquery_vars {
.menu_bg {
background-color: $menu_bg;
}
.menu_hover {
background-color: $menu_hover;
}
}
And in a handy page template:
<span class="is_hidden" id="jquery_vars">
<span class="is_hidden menu_bg"></span>
<span class="is_hidden menu_hover"></span>
</span>
Finally this allows in a nearby jQuery script:
var menu_bg = $('#jquery_vars .menu_bg').css("background-color");
var menu_hover = $('#jquery_vars .menu_hover').css("background-color");
This is so ugly my dad is wearing a bag on his head.
jQuery can pull arbitrary CSS values from page elements; but those elements have to exist. I did try pulling some of these values from raw CSS without creating the spans in the HTML and jQuery came up with undefined
. Obviously, if these variables are assigned to "real" objects on your page, you don't really need the arbitrary #jquery_vars
element. At the same time, one might forget that .sidebar-left nice-menu li
is the vital element being use to feed variables to jQuery.
If someone has anything else, it's got to be cleaner than this...
If you use webpack you can use sass-loader to exportvariables like:
$animation-length-ms: $animation-length + 0ms;
:export {
animationMillis: $animation-length-ms;
}
and import them like
import styles from '../styles/animation.scss'
const millis = parseInt(styles.animationMillis)
https://blog.bluematador.com/posts/how-to-share-variables-between-js-and-sass/