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?
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.
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With