在 React 中使用全局 SASS 变量迁移到 Styled-Components

Migrating to Styled-Components with global SASS variables in React

我正在尝试慢慢将 Styled-Components 引入我现有的代码库中,该代码库严重依赖于全局 SASS 变量(部分导入到 main.scss)。

如何引用 SCSS 变量?以下无效:

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

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

export default Button;

我是不是从错误的角度来处理这个问题?

变量在.scss.sass中起着非常重要的作用,但功能不能扩展到文件之外。

相反,您必须创建一个单独的 .js 文件 例如: variable.js) 和将所有变量定义为一个对象。

我推荐使用 ThemeProvider 组件。我也从 sass 转向样式化组件。 Theming with styled-components 使用 React 的上下文 api 并且非常好。查看此文档 Styled Components Theming.

我写了一篇关于解决这个问题的文章。 https://medium.com/styled-components/getting-sassy-with-sass-styled-theme-9a375cfb78e8

基本上,您可以使用出色的 sass-extract library along with sass-extract-loader and the sass-extract-js 插件将全局 Sass 变量作为主题对象引入您的应用程序。

如果这是一个老问题,请原谅我,但我想我会在需要时为我的 .scssstyled-components 使用 CSS 变量。

基本用法:

声明一个全局变量(最好在_variables.scss

:root {
    --primary-color: #fec85b;
}

使用全局 属性:

.button {
    background-color: var(--primary-color);
}

const Button = styled.button`
    background-color: var(--primary-color);
`;

请注意双线--.