Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to import variables from javascript to sass or vice versa?

I am making a css grid system that relies on the concept of blocks. So I have a base file like:

$max-columns: 4; $block-width: 220px; $block-height: 150px; $block-margin: 10px; 

And it is used by a mixin:

@mixin block ($rows, $columns, $max-columns) {   display: block;   float: left;   margin: $block-margin 0 0 $block-margin;   box-sizing: border-box;   width: ($block-width * $columns) - $block-margin; } 

But I'd also like javascript to have access to the variables in the base file. I was thinking that I could make an invisible div, and give it the $block-width, $block-height, and $block-margin attributes and pull the values from there. But max-columns, doesn't map to anything directly, so I'd have to come up with a hacky way to render it in a div. Is there a cleaner way to share values from sass/css to javascript or vice versa?

like image 692
Jeremy Smith Avatar asked Feb 19 '12 23:02

Jeremy Smith


People also ask

Does Sass work with JavaScript?

The sass package on npm is a pure-JavaScript package built from the Dart Sass implementation. In addition to Dart Sass's command-line interface, it provides a JavaScript API that can be used to drive Sass compilations from JavaScript.

Can you import variables in JavaScript?

The syntax we're using to export and import variables is called JavaScript modules. In order to be able to import a variable from a different file, it has to be exported using a named or a default export. The example above uses a named export and a named import.

Can you import SCSS into Sass?

The Sass @import directive extends the CSS @import rule so that it works with . scss and . sass files. It imports the file referenced and any variables or mixins that are defined in the imported file so they can be used in the main file.


Video Answer


1 Answers

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/

like image 182
velop Avatar answered Sep 21 '22 06:09

velop