CSS-in-JS 的库是如何工作的?

开发 前端
CSS-in-JS 的库是如何工作的?是什么让 Material UI 选择了 CSS-in-JS 的方式开发组件库?这不禁引起了笔者的好奇,于是决定探索一番,实现一个自己的 CSS-in-JS 库。

前言

笔者近期学习 Material UI 的过程中,发现 Material UI 的组件都是使用 CSS-in-JS 的方式编写的,联想到之前在社区里看到过不少批判 CSS-in-JS 的文章,对此有些惊讶。

CSS-in-JS 的库是如何工作的?是什么让 Material UI 选择了 CSS-in-JS 的方式开发组件库?

这不禁引起了笔者的好奇,于是决定探索一番,实现一个自己的 CSS-in-JS 库。

调研

目前社区中流行的 CSS-in-JS 库主要有两款:

  •  emotion
  •  styled-components

两者的 API 基本一致,鉴于 emotion 的源码中 JavaScript、Flow、TypeScript 三种代码混在一起,阅读起来实在是为难笔者,因此果断放弃了学习 emotion 的念头。

那么就以 styled-components 为学习对象,看看它是如何工作的。

styled-components 核心能力

使用方式

打开 styled-components 官方文档[1],点击导航栏的 Documentation[2],找到 API Reference[3] 一栏,第一个展示的就是 styled-components 的核心 API——styled,用法相信了解 React 的同学或多或少接触过:

const Button = styled.div`
background: palevioletred;
border-radius: 3px;
border: none;
color: white;
`;
const TomatoButton = styled(Button)`
background: tomato;
`;

通过在 React 组件中使用模板字符串编写 CSS 的形式实现一个自带样式的 React 组件。

抽丝剥茧

clone styled-components 的 GitHub Repo[4] 到本地,安装好依赖后用 VS Code 打开,会发现 styled-components 是一个 monorepo,核心包与 Repo 名称相同:

直接从 src/index.ts 开始查看源码:

默认导出的 styled API 是从 src/constructors/styled.tsx 导出的,那么继续向上溯源。

src/constructors/styled.tsx 中的代码非常简单,去掉类型并精简后的代码如下:
import createStyledComponent from '../models/StyledComponent';
// HTML 标签列表
import domElements from '../utils/domElements';
import constructWithOptions from './constructWithOptions';
// 构造基础的 styled 方法
const baseStyled = (tag) =>
constructWithOptions(createStyledComponent, tag);
const styled = baseStyled;
// 实现 HTML 标签的快捷调用方式
domElements.forEach(domElement => {
styled[domElement] = baseStyled(domElement);
});
export default styled;

从 styled API 的入口可以得知,上面使用方法[5]一节中,示例代码:

const Button = styled.div`
background: palevioletred;
border-radius: 3px;
border: none;
color: white;
`;

实际上与以下代码完全一致:

const Button = styled('div')`
background: palevioletred;
border-radius: 3px;
border: none;
color: white;
`;

styled API 为了方便使用封装了一个快捷调用方式,能够通过 styled[HTMLElement] 的方式快速创建基于 HTML 标签的组件。

接下来,继续向上溯源,找到与 styled API 有关的 baseStyled 的创建方式:

const baseStyled = (tag) =>
constructWithOptions(createStyledComponent, tag);

找到 constructWithOptions 方法所在的 src/constructors/constructWithOptions.ts,去掉类型并精简后的代码如下:

import css from './css';
export default function constructWithOptions(componentConstructor, tag, options) {
const templateFunction = (initialStyles, ...interpolations) =>
componentConstructor(tag, options, css(initialStyles, ...interpolations));
return templateFunction;
}

精简后的代码变得异常简单,baseStyled 是由 constructWithOptions 函数工厂创建并返回的。constructWithOptions 函数工厂的核心其实是 templateFunction 方法,其调用了组件的构造方法 componentConstructor,返回了一个携带样式的组件。

至此,即将进入 styled-components 的核心,一起抽丝剥茧一探究竟。

核心源码

constructWithOptions 函数工厂调用的组件构造方法 componentConstructor 是从外部传入的,而这个组件构造方法就是整个 styled-components 的核心所在。

在上面的源码里,baseStyled 是将 createStyledComponent 这个组件构造方法传入 componentConstructor 后返回的 templateFunction,templateFunction 的参数就是通过模板字符串编写的 CSS 样式,最终会传入组件构造方法 createStyledComponent 中。

文字描述非常混乱,画个图来梳理一下创建一个带有样式的组件的流程:

也就是说,当用户使用 styled API 创建带有样式的组件时,本质上是在调用 createStyledComponent 这个组件构造函数。

createStyledComponent 的源码在 src/models/StyledComponent.ts 中,由于源码较为复杂,详细阅读需要移步 GitHub:

styled-components/StyledComponent.ts at main · styled-components/styled-components[6]

从源码可以得知,createStyledComponent 的返回值是一个带有样式的组件 WrappedStyledComponent,在返回这个组件之前对其做了一些处理,大部分都是设置组件上的一些属性,可以在查看源码的时候暂时跳过。

从返回值向上溯源,发现 WrappedStyledComponent 是使用 React.forwardRef 创建的一个组件,这个组件调用了 useStyledComponentImpl 这个 Hook 并返回了 Hook 的返回值。

继续从返回值向上溯源,发现 useStyledComponentImpl Hook 中的大部分代码都是与我们了解 styled-components 是如何工作这件事情无关的代码,都是可以在查看源码的时候暂时跳过的部分,但是有一个 Hook 的名称让笔者觉得就是整个 styled-components 最核心的部分:

const generatedClassName = useInjectedStyle(
componentStyle,
isStatic,
context,
process.env.NODE_ENV !== 'production' ? forwardedComponent.warnTooManyClasses : undefined
);

在撰写本文之前,笔者大致知道 CSS-in-JS 的库是通过在运行时解析模板字符串并且动态创建 <style></style> 标签将样式插入页面中实现的,从 useInjectedStyle Hook 的名称来看,其行为就是动态创建 <style></style> 标签并插入页面中。

深入 useInjectedStyle,去掉类型并精简后的代码如下:

function useInjectedStyle(componentStyle, isStatic, resolvedAttrs, warnTooManyClasses) {
const styleSheet = useStyleSheet();
const stylis = useStylis();
const className = isStatic
? componentStyle.generateAndInjectStyles(EMPTY_OBJECT, styleSheet, stylis)
: componentStyle.generateAndInjectStyles(resolvedAttrs, styleSheet, stylis);
return className;
}

useInjectedStyle 调用了从参数传入的 componentStyle 上的 generateAndInjectStyles 方法,将样式传入其中,返回了样式对应的 className。

进一步查看 componentStyle,是在 createStyledComponent 中被实例化并传入 useInjectedStyle 的:

const componentStyle = new ComponentStyle(
rules,
styledComponentId,
isTargetStyledComp ? styledComponentTarget.componentStyle : undefined
);

因此 componentStyle 上的 generateAndInjectStyles 实际上是 ComponentStyle 这个类的实例方法,对应的源码比较长也比较复杂,详细阅读需要移步 GitHub,核心是对模板字符串进行解析,并将类名 hash 后返回 className:

styled-components/ComponentStyle.ts at main · styled-components/styled-components[7]

核心源码至此就已经解析完成了,其余部分的源码主要是为了提供更多基础功能以外的 API,提高可用度。

solid-sc 实现

解析完 styled-components 的核心源码后,回归到 CSS-in-JS 出现的原因上,最重要的因素可能是 JSX 的出现,在前端领域里掀起了一股 All in JS 的浪潮,就此诞生了上文中提到的 CSS-in-JS 的库。

那么,我们是否可以理解为 CSS-in-JS 与 JSX 属于一个绑定关系?

无论这个问题的答案如何,至少能够使用 JSX 语法的前端框架,都应该能够使用 CSS-in-JS 的技术方案。

近期笔者也在研究学习 SolidJS,希望能够参与到 SolidJS 的生态建设当中,注意到 SolidJS 社区中暂时还没有能够对标 emotion/styled-components 的 CSS-in-JS 库,虽然已经有能够满足大部分需求的 Solid Styled Components 了:

https://github.com/solidjs/solid-styled-components[8]

但是只是会用不是笔者的追求,笔者更希望能够尝试自己实现一个,于是就有了 MVP 版本:

learning-styled-components/index.tsx at master · wjq990112/learning-styled-components[9]

不熟悉 SolidJS 的同学可以暂时将其当做 React 来阅读,核心思路上文其实已经解析过了,本质上就是将组件上携带的样式在运行时进行解析,给一个独一无二的 className,然后将其塞到 <style> 标签中。

MVP 版本中只有两个函数:

const createClassName = (rules: TemplateStringsArray) => {
return () => {
className++;
const style = document.createElement('style');
style.dataset.sc = '';
style.textContent = `.sc-${className}{${rules[0]}}`.trim();
document.head.appendChild(style);
return `sc-${className}`;
};
};
const createStyledComponent: StyledComponentFactories = (
tag: keyof JSX.IntrinsicElements | Component
) => {
return (rules: TemplateStringsArray) => {
const StyledComponent: ParentComponent = (props) => {
const className = createClassName(rules);
const [local, others] = splitProps(props, ['children']);
return (
<Dynamic component={tag} class={className()} {...others}>
{local.children}
</Dynamic>
);
};
return StyledComponent;
};
};

两个函数的职责也非常简单,一个用于创建 <style> 标签并给样式生成一个唯一的 className,另一个用于创建经过样式包裹的动态组件。

当然,MVP 版本要成为 SolidJS 社区中能够对标 emotion/styled-components 的 CSS-in-JS 库,还有非常多工作要做,比如:

  •  运行时解析不同方式传入的 CSS 规则
  •  缓存相同组件的 className,相同组件复用样式
  •  避免多次插入 <style> 标签,多个组件样式复用同一个
  •  &etc.

不过,至少开了个好头,MVP 版本能够跑通 styled-components 文档中 Getting Started[10] 部分的示例:

learning-styled-components - StackBlitz[11]

MVP 版本的源代码在 https://github.com/wjq990112/learning-styled-components 的 master 分支,如果后续时间和精力允许,会在其他分支上完善,或者单独开一个 Repo,不管怎么样,先挖个坑。

最后

在研究 styled-components 的过程中,我发现社区中对 CSS-in-JS 的技术方案意见非常两极分化,喜欢的同学非常喜欢,讨厌的同学也非常讨厌。

笔者本人也在思考,为什么 CSS-in-JS 会这么流行,以至于 Material UI 也选择了这样的技术方案。

笔者认为可能有以下几个原因:

  •  不需要 CSS 预处理器实现复杂的样式组合
  •  不需要冗长的 CSS 规则约束 className
  •  构建产物中没有 CSS 文件,不需要单独引入组件样式

但 CSS-in-JS 的技术方案弊端也比较明显,毕竟需要在运行时解析样式并动态插入到页面中,而且 JS bundle 体积也会增大,加载过程会阻塞页面渲染。

展望

目前社区内的样式解决方案多以原子化 CSS 为主,原子化的形式能够有效减小样式体积,在编译阶段去掉没有使用到的样式,结合上文中提到的 CSS-in-JS 的技术方案的弊端,或许将 CSS-in-JS 运行时解析样式的部分,放到编译阶段进行处理,生成由原子化的样式组成的 CSS 文件,会是一个值得尝试的优化方向。

责任编辑:庞桂玉 来源: 大淘宝前端技术
相关推荐

2021-02-11 09:01:32

CSS开发 SDK

2022-11-11 08:16:51

2022-11-28 08:50:13

2022-03-22 09:07:34

开发CSS技术

2023-11-01 08:36:07

CSSTailwind

2021-02-01 08:36:19

JS引擎V8

2023-01-31 16:43:31

​Node.js事件循环

2011-08-08 13:45:58

jQuery

2021-05-10 17:20:55

AIOps开发人员人工智能

2023-03-06 00:27:02

Kubernetesscheduler系统

2010-08-02 16:56:03

ICMP协议

2023-04-18 14:53:48

2023-04-18 15:09:50

2021-08-03 14:29:30

ARPANET互联网协议TCP

2020-04-21 14:00:25

HTMLCSSJS

2021-02-23 14:56:12

数据库存储索引

2022-09-16 00:11:45

PyTorch神经网络存储

2017-11-17 09:13:31

Java注解

2022-05-18 08:00:00

JavaScriptFetch数据

2024-02-22 08:00:00

SoraOpenAI
点赞
收藏

51CTO技术栈公众号