@ibiz-template/scss-utils
v0.0.2
Published
scss BEM 规范工具包
Readme
SCSS BEM 规范工具包
样式规范
名称使用 BEM 规范。在 ts 中书写样式使用 useNamespace 工具方法,不可以直接在 class 中写样式。在 scss 中使用 scss 中提供的全局方法,不可已直接写组件中的样式。
BEM 命名规范
BEM 的意思就是块(block)、元素(element)、修饰符(modifier),是由 Yandex 团队提出的一种前端命名方法论。这种巧妙的命名方法让你的 CSS 类对其他开发者来说更加透明而且更有意义。BEM 命名约定更加严格,而且包含更多的信息,它们用于一个团队开发一个耗时的大项目。
说明
.block {/* 块 */}
.block__element {/* 元素 */}
.block__element--modifier {/* 修饰符 */}__ 与 -- 的区别
- __ 表示的是下级元素
- -- 表示元素的不同状态
代码中使用
在 ts 中使用 BEM
在全局提供了 useNamespace 方法,只需在组件实例化时使用此方法构造 ns 输出对象即可。
const ns = useNamespace('layout');
// bem class 命名
ns.b() => 'ibiz-layout'
ns.b('header') => 'ibiz-layout-header'
ns.e('header') => 'ibiz-layout__header'
ns.m('hover') => 'ibiz-layout--hover'
ns.be('header', 'title') => 'ibiz-layout-header__title'
ns.em('title', 'hover') => 'ibiz-layout__title--hover'
ns.bm('header', 'hover') => 'ibiz-layout-header--hover'
ns.bem('header', 'title', 'hover') => 'ibiz-layout-header__title--hover'
// 状态 class 样式命名
ns.is('loading', false) => ''
ns.is('loading', true) => 'is-loading'
// css 变量 style 对象
ns.cssVar({ 'color': 'red' }) => { '--ibiz-color': 'red' }
ns.cssVarBlock({ 'color': 'red' }) => { '--ibiz-layout-color': 'red' }
// css var 变量名称拼接
ns.cssVarName('color') => '--ibiz-color'
ns.cssVarBlockName('color') => '--ibiz-layout-color'在 scss 中使用 BEM
/**
.ibiz-layout { font-size: 14px; }
*/
@include b('layout') {
font-size: 14px;
}
/**
.ibiz-layout { font-size: 14px; }
.ibiz-layout__header { font-size: 14px; }
*/
@include b('layout') {
font-size: 14px;
@include e('header') {
font-size: 14px;
}
}
/**
.ibiz-layout { font-size: 14px; }
.ibiz-layout__header { font-size: 14px; }
.ibiz-layout__header--hover { color: red; }
*/
@include b('layout') {
font-size: 14px;
@include e('header') {
font-size: 14px;
@include m('hover') {
color: red;
}
}
}
/**
.ibiz-layout .is-loading { display: block; }
*/
@include b('layout') {
@include when('loading') {
display: block;
}
}注意 scss 在编译后,上边写法是不会出现嵌套的。如需嵌套需要使用下边的方式
/**
.ibiz-layout .ibiz-block__element--modifier { display: block; }
*/
@include b('layout') {
#{bem('block', 'element', 'modifier')} {
display: block;
}
}在 scss 使用 css 变量
#{joinVarName(('button', 'text-color'))} => '--ibiz-button-text-color'
#{getCssVarName('button', 'text-color')} => '--ibiz-button-text-color'
#{getCssVar('button', 'text-color')} => var(--ibiz-button-text-color)
#{getCssVarWithDefault(('button', 'text-color'), red)} => var(--ibiz-button-text-color, red)