Extract global variables from Sass stylesheets into a JS object.
I work on a team that uses Sass. We've got a shared variables file that gets referenced throughout our styleguide and in our components. I wanted to start using styled-components in some projects and wanted to keep things consistent but I didn't want to have to copy our Sass variables over. With this package I can simply reference our shared variables file and it will be converted into a JS object that gets passed down to my components via styled-components'
Cool! How do I get it?
$ yarn add sass-styled-theme
(npm install works too)
Nice! How do I use it?
Wrap your App in a ThemeProvider component like this:
// Import the libimport sassToStyledTheme from 'sass-styled-theme';// Call the function with absolute path to your Sass fileconst theme = ;// Pass the theme into your ThemeProvider component;
Then use themes in your styled components:
;const Button = styledbutton`background-color:`;
Sweet! What does the output look like?
Given a Sass file with some global variable declarations:
It will yield the following object:
primary: 'rgb(255, 202, 77)'seondary: 'rgb(26, 147, 200)''primary-light': 'rgb(255, 232, 179)''base-padding': '10px''base-margin': '0 1em''base-border': '1px solid rgb(204, 204, 204)''font-family-sans': '\'Helvetica\', \'Arial\', sans-serif''base-font-size': '16px''line-height': '28.8px'
Rad! Can I customize it?
You want options? Sure. The
sassToStyledTheme function takes an options object as its second parameter.
const theme = ;
|camel||boolean||false||convert output variable names to camelCase|
|sassOptions||object||options to pass thru to node-sass|
Help! It's not working for me.
This project is open source. I've tried to make sure it works for a lot of use cases (read: mine) but if I missed yours, feel free to open an issue. Better yet, submit a PR! Seriously, any feedback and help is welcome.
This library uses the awesome sass-extract package under the hood to render and parse the Sass. There is currently an issue where mixins or functions that use default values may cause the variable extraction to silently fail (sass-extract #12). If you run into this, a workaround is to make sure that you follow the mixin or function with a normal variable declaration.