I eventually figured this out, so here's how you can do it, at least if using React.
You need to define the variables in one file and export them.
// Variables.js
export const FONTSIZE_5 = '20px';
Then you need to import those variables into each component file.
// Button.js
import * as palette from './Variables.js';
Then you can use the variables in your styled-components like this:
const Button = styled.button`
font-size: ${palette.FONTSIZE_5};
`;
Answer from colmtuite on Stack OverflowI eventually figured this out, so here's how you can do it, at least if using React.
You need to define the variables in one file and export them.
// Variables.js
export const FONTSIZE_5 = '20px';
Then you need to import those variables into each component file.
// Button.js
import * as palette from './Variables.js';
Then you can use the variables in your styled-components like this:
const Button = styled.button`
font-size: ${palette.FONTSIZE_5};
`;
Wrapping a <ThemeProvider> around your application may help:
https://www.styled-components.com/docs/advanced#theming
const theme = {
fontColour: 'purple'
}
render() {
return (
<ThemeProvider theme={theme}>
<MyApplication />
</ThemeProvider>
)
}
That will give all child styled-components access to the theme like so:
const MyApplication = styled.section`
color: ${props => props.theme.fontColour}
`
Or
const MyFancyButton = styled.button`
background: ${props => props.theme.fontColour}
`
Or access the theme via https://www.styled-components.com/docs/advanced#getting-the-theme-without-styled-components
Using CSS variable with styled-components - Stack Overflow
reactjs - Migrating to Styled-Components with global SASS variables in React - Stack Overflow
reactjs - How to use external css variables in styled-components? - Stack Overflow
Styled Components: Global Colors Style Sheet
Videos
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.
Pardon me if this is an old question but I thought I chip in on how I use CSS variables for both my .scss and styled-components when the need arises.
Basic Usage:
Declaring a global variable (preferably at _variables.scss)
:root {
--primary-color: #fec85b;
}
Using the global property:
.button {
background-color: var(--primary-color);
}
or
const Button = styled.button`
background-color: var(--primary-color);
`;
Please pay attention to the double line --.