likes
comments
collection
share

css or css in js ?

作者站长头像
站长
· 阅读数 15

第一次发文章,力求简单明了,不讲废话。

emotion

css in js 库有很多种, 比较著名的就是 emotion, 但通过 Sam Magura 的文章 可知这类库的优缺点都很明显

优点

  • css 模块化 (重要功能)
  • 与 js 代码合在一起 (不用单独写 css 文件, 感觉可能更难维护...)
  • 能将 js 变量应用到样式上 (React 也能做到, 不过只能是 inline-style)

缺点

  • 性能问题 (忍不了)
  • 样式权重问题 (影响样式覆盖, 基础库不能容忍此缺点)
  • 增加了包体积 8kb (略微牵强, 可忽略)

为什会有性能问题 ?

css in js 会将 css 转换为 hash 值, 每次页面更新都需要重新序列化得到 css 后再次计算 hash, 因此增加了额外的性能开销, 例如下面的 style

<style data-emotion="css mj4qsp" data-s>
.css-mj4qsp {
  display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display: flex;-webkit-align-items: center;
  -webkit-box-align: center;-ms-flex-align:center;align-items: center;border-bottom: 1px solid rgba(5, 5, 5, 0.06);
  padding-inline: 24px! important;height: 48px; line-height: 48px; background: transparent! important;
}
</style>

怎么解决 ?

将 hash 缓存起来, 不就好了? 因此 antd 给出了方案

antd-style

通过缓存的方法去减少序列化 css 的次数, 只关注 antd version 和 token, 当二者改变时才重新计算 hash

如果样式是受控的怎么办 ?

这个问题其实很简单, 每个组件都是一个独立的存在, 无论怎么受控, 样式都是存在于组件内的, 因此我们给组件做缓存即可。(props.style 不是 css in js)

antd-style 就是完美的吗?

antd-style 基于 emotion, 但它有一下优缺点

优点

  • 性能好
  • 兼容 antd5 token
  • 更适合基于 antd 二次封装的组件库, createInstance 发挥了重要作用
  • 样式覆盖优秀 (:where)

缺点

  • 组件级: 需要独特的 key
  • 不能直接复写样式, 需要先传 className, 如果组件不支持 className 就难受了
  • 兼容性差 :where 兼容性
  • 综上: 只适合组件库

结论 —— 如何选择 css in js

基础组件库、基于 antd 二次封装的组件库: 毫无疑问, antd-style 是首选

业务项目: 首先抉择好性能问题, 并且 antd-style 一定不适合