bem.scss 这个sass工具要如何使用,给出使用文档和示例
constants.scss
$namespace: 'longmo' !default;
$common-separator: '-' !default;
$element-separator: '__' !default;
$modifier-separator: '--' !default;
$state-prefix: 'is' !default;
bem.scss
@forward './constants';
@mixin b($block) {
$B: $namespace + '-' + $block !global;
.#{$B} {
@content;
}
}
@mixin e($name) {
@at-root {
&#{$element-separator}#{$name} {
@content;
}
}
}
@mixin m($name) {
@at-root {
&#{$modifier-separator}#{$name} {
@content;
}
}
}
// block__element.is-active {}
@mixin is($state, $prefix: $state-prefix) {
@at-root {
&.#{$prefix}-#{$state} {
@content;
}
}
}
这段Sass代码定义了一组混合宏(mixins),用于实现BEM命名约定的便捷使用,同时也支持了命名空间、元素分隔符、修饰符分隔符和状态前缀等自定义选项。
下面是如何使用这些工具的文档和示例。
使用文档
1. 引入文件
首先,你需要确保已经通过@forward './constants';引入了必要的常量定义文件(如命名空间、分隔符等)。请确认该文件中已定义了如下变量:
$namespace$element-separator$modifier-separator$state-prefix
2. Mixin 描述
-
b($block): 定义一个块级元素。
- 参数:
$block: 块名。
- 全局变量
$B将被设置为namespace-block的形式。
- 参数:
-
e($name): 定义块内的元素。
- 参数:
$name: 元素名称。
- 使用当前父选择器(由
@at-root和&组合提供)加上元素分隔符和元素名构建选择器。
- 参数:
-
m($name): 定义块或元素的修饰符。
- 参数:
$name: 修饰符名称。
- 同样基于当前父选择器构建修饰符的选择器。
- 参数:
-
is($state, $prefix: $state-prefix): 定义组件的状态。
- 参数:
$state: 状态名称。$prefix: 可选参数,默认使用$state-prefix变量值作为前缀。
- 参数:
示例
假设你有以下CSS规则要转换为Sass,并且你的命名空间是product,元素分隔符是__,修饰符分隔符是--,状态前缀是is。
原始CSS
.product-card {
color: #333;
}
.product-card__title {
font-size: 24px;
}
.product-card__image--large {
width: 500px;
}
.product-card.is-active {
border: 2px solid blue;
}
使用Sass Mixins后的版本
// 引入必要的配置
@forward './constants';
@include b(card) {
color: #333;
@include e(title) {
font-size: 24px;
}
@include e(image) {
@include m(large) {
width: 500px;
}
}
@include is(active) {
border: 2px solid blue;
}
}
在这个例子中,我们使用了b, e, m, 和 is 这些mixin来简化BEM风格的CSS编写过程。注意,在实际应用中,你需要确保所有使用的变量(如$namespace, $element-separator, $modifier-separator, $state-prefix)已经在导入的constants文件中正确定义。这将帮助你保持代码的一致性和可维护性,特别是在大型项目或多团队协作环境中尤为重要。

浙公网安备 33010602011771号