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

e278eaafd04f44223923a543f93a8af3.gif

本文将介绍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 库主要有两款:

  1. emotion

  2. styled-components

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

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

styled-components 核心能力

▐  使用方法

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

官方文档地址:https://styled-components.com/

Documentation地址:https://styled-components.com/docs

API Reference地址:https://styled-components.com/docs/api

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 到本地,安装好依赖后用 VS Code 打开,会发现 styled-components 是一个 monorepo,核心包与 Repo 名称相同:

GitHub Repo地址:https://github.com/styled-components/styled-components


e4d0cf1bd3cbb695cc9b48bd6a85b8e0.png

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

6844819a5718b3b5f1d5c052c607ada9.png

默认导出的 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 的入口可以得知,上面使用方法一节中,示例代码:

使用方法地址:https://www.notion.so/CSS-in-JS-8d64aa49e0554607b596de753bcabee8

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 后返回的 templateFunctiontemplateFunction 的参数就是通过模板字符串编写的 CSS 样式,最终会传入组件构造方法 createStyledComponent 中。

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

ae2c7a1af5d7fa6f34393f7cbfd9db55.png

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

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

styled-components/StyledComponent.ts at main · styled-components/styled-components

从源码可以得知,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

核心源码至此就已经解析完成了,其余部分的源码主要是为了提供更多基础功能以外的 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

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

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

不熟悉 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 库,还有非常多工作要做,比如:

  1. 运行时解析不同方式传入的 CSS 规则

  2. 缓存相同组件的 className,相同组件复用样式

  3. 避免多次插入 <style> 标签,多个组件样式复用同一个

  4. &etc.

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

learning-styled-components - StackBlitz

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

Getting Started地址:https://styled-components.com/docs/basics#getting-started

learning-styled-components - StackBlitz地址:

最后

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

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

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

  1. 不需要 CSS 预处理器实现复杂的样式组合

  2. 不需要冗长的 CSS 规则约束 className

  3. 构建产物中没有 CSS 文件,不需要单独引入组件样式

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

展望

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

团队介绍

大淘宝跨端技术部终端框架 & Web 容器团队,负责大淘宝的前端架构 + 手淘核心的 Web 容器,面向整个阿里巴巴集团提供开发者 & 用户体验支持,业务场景非常丰富。
核心产品包括前端框架飞冰(ICE)、Rax.js,业内领先的调试工具 AppDevTools 等。研究领域涉及前端框架、调试工具、W3C 标准、Web 容器、WebKit 内核、Flutter 等各种前沿技术。
这里有开放的学习心态和积极拥抱开源社区的氛围,还有一群追求极致体验的小伙伴,期待你的加入!

✿  拓展阅读

1d3fea20b24a9a1d8ece68166b14b8cd.jpeg

5ca8bc914d1b1e0769bb207dab4fa699.jpeg

作者|王家祺(炽翎)

编辑|橙子君

3ed31bc94caab8fe2022f433776e4671.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值