React 中的 CSS 模块 - 共享可重用代码的解决方案

flo*_*roz 5 javascript css sass reactjs css-modules

我正在将我的项目中的全局 SASS 迁移到 SCSS 模块中,该项目混合了全局 scss 和某种自定义的类似引导程序的框架。

我在应用程序中到处都有需要重构的全局样式引用

在此输入图像描述

我的目标是跨 CSS 模块共享样式以重用主题、按钮等。 不幸的是,CSS 模块的“组合”功能无法编译 SASS

在此输入图像描述

在此输入图像描述

这似乎是一个已知问题:

https://github.com/facebook/create-react-app/issues/7596

跨 CSS 模块快速引用共享 .scss 类的最佳策略是什么?

我有 main.scss,我在其中加载全局应用程序中使用的文件:

    :global {
      @import './button';
    }

Run Code Online (Sandbox Code Playgroud)

在 sass/_button.scss 中:


    .btn {
      font-family: $baseFont;
      font-size: $text--m;
      font-weight: normal;
      text-align: center;
      outline: none;
      white-space: nowrap;
      padding: $padding--xs $padding--m;
      color: var(--white);
      background-color: var(--dark-blue);
      border: 1px solid var(--sky-blue-dark);
      border-radius: 4px;
      transition: all 100ms, color 100ms;
      box-shadow: 2px 3px 6px 0 var(--black-half);
      cursor: pointer;


Run Code Online (Sandbox Code Playgroud)

在我的 Header.jsx 组件中


    <div className={styles.popContainer}>
            <button
              className={`btn ${styles.actionButton}`}
              onClick={toggleActionMenu}
            >
            Click
            </button>
            </div>

Run Code Online (Sandbox Code Playgroud)

我希望能够从类中删除“btn”并仅使用该模块

在我的 Header.module.scss 中

@import '../../../../styles/buttons.scss';

.header {
}

.actionButton {
  @include btn();
  @include btn__primary();
}
Run Code Online (Sandbox Code Playgroud)

使用 mixins 是可行的,但它很快就会变得很麻烦,因为您必须在每个文件中导入 mixin,并且可能有几个我想重用的文件。此外,mixins 将复制整个样式,从而扩大包的大小。