Webpack + postcss +主题+热重装

Fir*_*Dib 5 css themes reactjs webpack postcss

我想允许用户在我的网站上选择主题,他们将通过下拉菜单来做.我目前无法弄清楚如何支持这个功能,但没有编写愚蠢的代码.

我目前使用css-modules和postcss来让我的生活更轻松.Webpack用于将所有内容捆绑在一起.我在开发过程中使用热重新加载,在此期间我使用样式加载器.

完整配置如下所示

{
  test: /\.css$/,
  loader: !isDev
    ? ExtractTextPlugin.extract('style-loader', 'css-loader?sourcemap&minimize&modules&importLoaders=1&localIdentName=[name]-[local]-[hash:base64:5]!postcss-loader')
    : 'style-loader!css-loader?sourcemap&minimize&modules&importLoaders=1&localIdentName=[name]-[local]-[hash:base64:5]!postcss-loader'
},
Run Code Online (Sandbox Code Playgroud)

解决方案1

在body标记上放置一个classname以确定加载了哪个主题.然后,这用于从每个组件css内部选择正确的主题.这是非常乏味的,我想避免的,但它看起来像这样:

.myComponent {
  margin: 10px;
  width: 100px;
}

:global(.theme1) {
  .myComponent {
    background: $theme1_myComponent_background;
  }
}

:global(.theme2) {
  .myComponent {
    background: $theme2_myComponent_background;
  }
}
Run Code Online (Sandbox Code Playgroud)

这很快就会变成难以扩展和不可维护的东西,这就是为什么我要避免它.

解决方案2

为css生成预定义的静态包.当用户请求/main.css时,服务器上的处理程序确定要发送的主题(也许查询字符串),并将它们发送theme1-main.csstheme2-main.css或类似的规定.问题是我不知道如何支持开发环境.

关于这一点的好处是我的css文件不需要任何额外的和难以维护的逻辑:

.myComponent {
  margin: 10px;
  width: 100px;
  background: $myComponent_background;
}
Run Code Online (Sandbox Code Playgroud)

解决方案3

使用本机css变量.然后可以在运行时更新这些内容,这将反映已经加载的css并在生产和开发环境中正常工作.我的组件也看起来像(或类似)解决方案2.这里的问题是它们本身并没有得到广泛支持,我不确定是否有任何值得研究的polyfill会为我做这类事情.


总而言之,这些是我的想法.我还没有得出任何明确的结论,并希望得到关于如何解决这个问题的所有反馈.也许我正在考虑这一切都错了,并且有更好的方法来做我想做的事情.

提前致谢!

Tom*_*rez 0

这是使用 SASS 的解决方案。它基本上是您的解决方案 1,但更容易编写和维护。看来您没有使用 SASS,但由于它是我能为个人使用找到的最佳解决方案,我认为值得分享...

这是 SCSS 代码(此处为 CodePen):

// Define theme variables

$themes: (
  default: ( // default theme
    bg-color: white,
    text-color: black,
  ),
  dark: (
    bg-color: black,
    text-color: white,
  ),
  colorful: (
    bg-color: green,
    text-color: orange,
  )
);

// This is how you use your themes

.example{
  padding: 10px;
  @include themify {
    background: theme-get(bg-color);
    color: theme-get(text-color);
  }
}
Run Code Online (Sandbox Code Playgroud)

它需要这个才能工作:

@mixin themify() {
  // Iterate over the themes
  @each $theme-name, $theme in $themes {
    $current-theme: $theme !global;
    @if $theme-name == 'default' {
      @content;
    } @else {
      .theme-#{$theme-name} & {
        @content;
      }
    }
  }
}

@function theme-get($key, $theme: $current-theme) {
  $ret: map-get($theme, $key);
  @if not $ret {
    @error 'Your theme doesn\'t have a value for `#{$key}`.';    
  }
  @return $ret;
}
Run Code Online (Sandbox Code Playgroud)

生成的 CSS:

.example {
  padding: 10px;
  background: white;
  color: black;
}
.theme-dark .example {
  background: black;
  color: white;
}
.theme-colorful .example {
  background: green;
  color: orange;
}
Run Code Online (Sandbox Code Playgroud)

这很大程度上受到以下启发: