SCSSの変数をexportしてJavaScript側で読み取ってメソッドで利用する
SCSS側で:export {}
したものを、
JavaScript側でimport
し、style.boxWidth
の様にアクセスすると使えます。
注意点
exportで読み取った値はstring型です。
数値として利用するには下記の様な感じで変換しましょう。
SCSS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | // 変数 $boxMargin: 20px; $boxWidth: 200px; // エクスポート :export { boxWidth: $boxWidth; boxMargin: $boxMargin; } // 普通のスタイル .header{ width: $boxWidth; margin: $boxMargin; } |
JavaScript
1 2 3 4 5 6 7 | import style from './scss/Header.scss'; // pxを取り除いてnumber型に変換 const cutPx = str => Number(str.replace('px', '')); console.log(cutPx(style.boxWidth)) // 200 console.log(cutPx(style.boxMargin)) // 20 |
この様にしてstyle側で指定した幅や余白に応じて何か処理するのはいかがでしょうか。