You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Sass列表分隔符与简洁@mixin编写:免引号传选择器问题

Solution for Passing Unquoted Selectors to Your Sass Namespace Mixin

Great question! The issue here is that when you pass .bar + .baz without quotes, Sass doesn’t treat it as a string—it parses it as a selector node (a special Sass data type), which your original str-replace function can’t process directly. Here’s how to adjust your mixin to handle unquoted selectors:

Modified Code

@mixin pre-assign($value) { $pre: $value !global; }
@include pre-assign('foo');

@function str-replace($string, $search, $replace: '') {
  $index: str-index($string, $search);
  @if $index {
    @return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
  }
  @return $string;
}

@mixin pre($value) {
  // Convert the selector node to a string, then strip surrounding quotes and leading whitespace
  $value-str: str-slice(inspect($value), 2, -2);
  // Apply your namespace replacement logic
  $result: str-replace($value-str, '.', '.#{$pre}-');
  // Output the final selector
  #{$result} { @content; }
}

How to Use It

Now you can call the mixin without quotes, exactly as you wanted:

@include pre(.bar + .baz) { display: none; }

Compiled Output

.foo-bar + .foo-baz { display: none; }

Key Changes Explained

  1. inspect($value): This function converts Sass’s selector node data type into a string representation. For .bar + .baz, it returns " .bar + .baz" (with leading space and surrounding quotes—output may vary slightly by Sass version, but the core behavior is consistent).
  2. str-slice(inspect($value), 2, -2): This strips the leading space and surrounding quotes from the string, leaving clean, unquoted selector text like .bar + .baz.
  3. Original Replacement Logic: With a proper string in hand, your existing str-replace function works as intended to prepend the namespace to each class selector.

Edge Case Testing

This fix handles common selector patterns seamlessly:

  • Pseudo-classes: @include pre(.bar:hover) compiles to .foo-bar:hover { ... }
  • Multi-class selectors: @include pre(.bar.baz) compiles to .foo-bar.foo-baz { ... }
  • Child selectors: @include pre(.bar > .baz) compiles to .foo-bar > .foo-baz { ... }

内容的提问来源于stack exchange,提问作者DanMad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:25:17