Exporting SCSS Variables to JS (auto looping variables)

Taking a Cue from Bootstrap 4, you could combine a SASS map with a loop like below;

/* Define all colours */
$theme-colours: (
  some-color: #000,
  another-color: #000,
  third-color: #000,
  fourth-color: #000
)

@each $color, $value in $theme-colours {
  :export{
    $color: $value;
  }
}

Here's some examples from the Bootstrap 4 Docs


Some improvements to the accepted answer:

  • Use camelcase so you will be able to individually export a variable.

  • Set the @each directive outside so it won't generate a new :export at-rule for each variable.


_variables.scss

$theme-colors: (
  'someColor': #000,
  'anotherColor': #FFF,
);

:export {
  @each $key, $value in $theme-colors {
    #{unquote($key)}: $value;
  }
}

app.js

import styles from './core-styles/brand/_variables.scss' // { anotherColor: "#FFF", someColor: "#000" }
import { someColor } from './core-styles/brand/_variables.scss' // #000

Side note: I prefer using quotes inside Sass Maps, but you can omit them.