用React Styled-Components导入scss变量的最佳方法?

时间:2019-01-09 18:48:03

标签: reactjs sass styled-components

在普通的React组件中,如果您有scss,则可以将其他scss文件导入到其中,并可以访问$color-primary: blue ...等

使用样式化组件执行此操作的最佳方法是什么?

让我说我要使用的应用程序有一些主要变量:字体大小,字体系列,颜色等。我希望能够将它们导入到React组件中并在样式化组件中使用该文件的?

我知道您可以在每个文件中设置变量并使用它们,但这违背了拥有“全局变量”并使用它们的目的。

从技术上讲,我知道样式化组件不是scss,因此您甚至可能无法导入scss文件并使用其中的变量-那么如何拥有所有样式化组件文件都可以导入的全局变量并使用?

3 个答案:

答案 0 :(得分:1)

我认为您想要拥有的是令牌文件,令牌用于组织“变量”,这些变量描述了设计系统https://www.lightningdesignsystem.com/design-tokens/#site-main-content中的属性。

幸运的是,这可以在javascript世界中非常简单地完成。几乎只需要创建一个文件,即可在其中声明所有这些常量,然后将其导出并在要使用的位置使用它:

我可以为您提供一个简单的解决方案:

// tokens.js

const tokens = {
  colorGray1: "#FF1100",
  colorGray2: "#CCC",
  colorGray3: "#DDD",
  colorGray4: "#EEE",
  colorBackgroundBlack: "#000",
}

export default tokens;

// app.js
import React from "react"
import styled from "styled-component";
import tokens from "./tokens.js" // this is somewhere in your app

const StyledComponent = styled.div`
  color: ${tokens.colorGray1},
  background: ${tokens.colorBackgroundBlack}
`

export default function MyComponent() {
  return <StyledComponent>This has grey color and black background</StyledComponent>
}

此外,样式化组件还有一个很好的库,名为polish,它可以模拟sass通常提供的https://polished.js.org/的混合和功能

祝你好运!

答案 1 :(得分:0)

To answer: "how do you have global variables that all styled-components files can import and use?"

You should setup a Theme that can be shared throughout your application via a ThemeProvider.

After that perhaps there's some magic where you can import your existing scss variables into the file where your theme is initiated and assign those existing vars as needed.... but TBH, I'd just stick to using a theme and kill scss (styled-component FTW)

答案 2 :(得分:0)

有一些Webpack加载器可以加载scss文件并将scss变量转换为js对象。我用过sass-values-loader

import styles from './style.scss';
import vars from '!!sass-vars-to-js-loader!./style.scss';

console.log(vars.colorPrimary);