如何在 CSS 模块中使用全局变量?

问题描述:

我正在忙着用 CSS 模块学习 React,但我不太明白如何存储变量?例如,在 Sass 中你可以这样做:

I'm busy learning React with CSS-Modules and I don't quite understand how one would store variables? For example, in Sass you're able to do this:

// _variables.scss
$primary-color: #f1f1f1; 

// heading.scss
@import './variables';
.heading {
  color: $primary-color
}

你如何在 CSS Modules 中实现这一点?

How do you achieve this in CSS Modules?

一种方法是使用依赖项.例如,

One way could be to use dependencies. For example,

// variables.css
.primaryColor {
  color: #f1f1f1
}

// heading.css
.heading {
  composes: primaryColor from "./variables.css"
}

在此处查看更多详细信息:https://github.com/css-modules/css-modules#dependencies

See more detailed information here: https://github.com/css-modules/css-modules#dependencies

如果您使用 webpack,这里有更多示例:https://github.com/webpack/css-loader#composing-css-classes

If you're using webpack there are more examples here: https://github.com/webpack/css-loader#composing-css-classes

此外,如果您使用 webpack,您仍然可以将 Sass 与 CSS 模块一起使用.

Also if you are using webpack you can still use Sass with CSS modules.