Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Migrating to Styled-Components with global SASS variables in React

I'm trying to slowly introduce Styled-Components into my existing codebase which relies heavily on global SASS variables (partials imported into a main.scss).

How do I reference the SCSS variables? The following doesn't work:

import React from 'react';
import styled from 'styled-components';

const Button = styled.button`
  background-color: $color-blue;
`;

export default Button;

Am I approaching this from the wrong way?

like image 515
skube Avatar asked Mar 09 '18 18:03

skube


2 Answers

Variables play a very important role in .scss or .sass, but the functionality cannot be extended outside the file.

Instead, you have to create a separate .js file (For example: variable.js) and define all your variables as an object.

like image 105
Yashu Mittal Avatar answered Sep 23 '22 02:09

Yashu Mittal


I wrote up an article about solving this very issue. https://medium.com/styled-components/getting-sassy-with-sass-styled-theme-9a375cfb78e8

Essentially, you can use the excellent sass-extract library along with sass-extract-loader and the sass-extract-js plugin to bring your global Sass variables into your app as a theme object.

like image 44
Adam Avatar answered Sep 21 '22 02:09

Adam