222 - 《styled-components vs. emotion》

发布于 2022年11月29日

背景是我们要做 CSS 方案的选择,经过前一篇文章的分析,大致选择了 CSS-in-JS 的方向,然后现在在 styled-components 和 emotion 之间做最终抉择。

1、使用数据上二者差不多,从下载量看,styled-components 每周 464 万,emotion 每周 433 万。styled-components 更老牌,但 emotion 后来居上后也不差。

2、写法上,二者都支持 style.element 和 css props 的形式。区别是 styled-components 优先推荐前者,而 emotion 优先推荐后者。同时他们也都支持 Object 风格的写法,个人比较倾向 CSS 风格,对从 CSS 过来的同学更友好,由于有编辑器插件的支持,语法高亮和提示都不是问题。

// 写法 1
const Div = styled.div`color: red`;
// 写法 2
<div css=`color:red` />
// CSS 风格
styled.div`color: red`;
// Object 风格
styled.div({ color: 'red' });

3、产物尺寸上 emotion 略小。styled-components gzip 后 12.7K(6.0 测试版降到 10.7K),emotion gzip 后 8.5K。

4、功能上大家也差不多,不存在一个能做另一个不能做的情况。比如动态样式、动态 tag、扩展样式、伪元素伪类嵌套媒体查询动画、主题、全局样式、SSR。但是 Variants 两个都是不支持。。

// 动态样式方法 1
const Button = styled.button`color: ${p => p.color}`;
<Button color="red" />;
// 动态样式方法 2,推荐,更简单,但要小心媒体查询的场景
const Button = styled.button`color: var(--color)`;
<Button style={{ '--color': 'red' }} />;
// 动态 Tag,作为 A 标签

内容预览已结束

此内容需要会员权限。请先登录以查看完整内容。