styled-jsx vs emotion vs glamorous vs styled-components
React CSS-in-JS 方案深度对比与架构选型指南
styled-jsxemotionglamorousstyled-components類似套件:

React CSS-in-JS 方案深度对比与架构选型指南

emotion、styled-components、styled-jsx 和 glamorous 都是 React 生态中用于解决组件样式隔离问题的 CSS-in-JS 方案,但它们的实现机制、运行时行为和适用场景截然不同。

emotion 是一个高性能、功能丰富的 CSS-in-JS 库,支持对象样式和字符串样式,以其优秀的服务端渲染(SSR)性能和灵活的 API 著称。

styled-components 是最流行的 CSS-in-JS 库之一,首创了标签模板语法,强调“样式即组件”的理念,拥有庞大的社区和生态系统。

styled-jsx 是 Vercel 为 Next.js 量身打造的方案,它将 CSS 限制在组件作用域内,并在构建时提取 CSS,几乎零运行时开销,特别适合 Next.js 项目。

glamorous 曾是 styled-components 的一个轻量级分支,由 PayPal 维护,但目前已正式废弃(Deprecated),官方建议迁移至 emotion 或其他现代方案,不应再用于新项目。

npm下載趨勢

3 年

GitHub Stars 排名

統計詳情

套件
下載數
Stars
大小
Issues
發布時間
許可
styled-jsx34,707,0847,7751.03 MB831 年前MIT
emotion0---6 年前MIT
glamorous03,616-08 年前MIT
styled-components041,0602.18 MB2614 天前MIT

React CSS-in-JS 终极对决:Emotion, Styled-Components, Styled-JSX 与 Glamorous

在 React 开发生涯中,如何管理组件样式一直是个难题。CSS-in-JS 方案应运而生,试图将样式直接写在 JavaScript 中,实现样式与组件的紧密绑定。今天我们要深入对比四个关键角色:emotion、styled-components、styled-jsx 以及已退场的 glamorous。我们将抛开表面的流行度,从架构原理、运行时行为和实际代码表现来剖析它们的优劣。

🚨 重要警示:关于 Glamorous 的现状

在深入技术细节之前,必须明确一点:glamorous 已不再适用。

glamorous 曾经是 styled-components 的一个轻量级替代品,由 PayPal 团队开发。然而,由于其维护成本高昂且功能逐渐被 emotion 超越,官方已在 npm 和 GitHub 上将其标记为 Deprecated(已废弃)。维护团队明确建议所有用户迁移到 emotion。

// ❌ 错误示范:在新项目中使用已废弃的库
import glamorous from 'glamorous';
const Title = glamorous.h1({ color: 'blue' });

// ✅ 正确做法:迁移至 emotion
import { css } from '@emotion/react';
const Title = (props) => <h1 css={{ color: 'blue' }} {...props} />;

结论:在任何新的架构决策中,直接排除 glamorous。以下的对比将聚焦于其余三个活跃且成熟的方案。

🏗️ 核心机制:运行时注入 vs 构建时提取

这是理解这些库差异的关键。emotion 和 styled-components 主要在运行时生成 CSS 并注入页面,而 styled-jsx 则在构建时提取 CSS。

emotion 和 styled-components 会在浏览器中运行一段 JavaScript 代码,监听组件渲染,动态计算样式字符串,然后创建 <style> 标签插入到 DOM 中。这意味着它们有一定的运行时开销,但换来了极强的动态能力。

// emotion: 运行时生成类名
import { css } from '@emotion/react';
function Box({ color }) {
  return <div css={css({ backgroundColor: color })} />;
}

// styled-components: 运行时生成带样样的组件
import styled from 'styled-components';
const Box = styled.div`background-color: ${props => props.color};`;

styled-jsx 则完全不同。它依赖 Babel 插件,在构建阶段扫描组件,提取 <style jsx> 标签内的 CSS,生成独立的 CSS 文件或将其打包,并在组件中只保留必要的类名引用。这使得它在运行时的负担极小。

// styled-jsx: 构建时提取,运行时仅挂载类名
function Box({ color }) {
  return (
    <div>
      <style jsx>{`
        div { background-color: ${color}; }
      `}</style>
    </div>
  );
}

🎨 开发体验:标签模板 vs 对象语法 vs 原生标签

不同的库提供了不同的编写样式的方式,这直接影响日常开发的流畅度。

styled-components 强制使用标签模板字符串(Tagged Templates)。这种方式让 CSS 看起来很像原生 CSS,支持嵌套和伪类,阅读体验很好,但失去了 JavaScript 对象的一些智能提示(除非配置了专门的 Babel 插件)。

// styled-components: 标签模板
const Button = styled.button`
  background: palevioletred;
  color: white;
  border-radius: 3px;
  
  &:hover {
    background: purple;
  }
`;

emotion 提供了双重模式。你既可以使用标签模板(类似 styled-components),也可以使用普通的 JavaScript 对象。对象语法对于习惯内联样式或需要复杂逻辑计算的开发者来说非常友好,且天然支持 TypeScript 类型推断。

// emotion: 标签模板模式
import styled from '@emotion/styled';
const Button = styled.button`
  background: palevioletred;
  color: white;
`;

// emotion: 对象语法模式
import { css } from '@emotion/react';
const buttonStyle = css({
  background: 'palevioletred',
  color: 'white',
  '&:hover': { background: 'purple' }
});

styled-jsx 要求你将 CSS 写在组件内部的 <style jsx> 标签中。这种写法最接近原生 HTML/CSS 结构,Scoped CSS 自动生效,不需要额外的类名绑定逻辑,但在组件外部复用样式稍显麻烦。

// styled-jsx: 组件内 style 标签
function Button() {
  return (
    <button>
      Click me
      <style jsx>{`
        button {
          background: palevioletred;
          color: white;
        }
        button:hover {
          background: purple;
        }
      `}</style>
    </button>
  );
}

⚡ 性能与 SSR:谁更快?

在服务端渲染(SSR)场景下,性能差异会被放大。

styled-jsx 由于是构建时提取 CSS,服务端只需要渲染 HTML 和引用已有的 CSS 文件(或内联关键的 CSS 块),不需要在执行服务端代码时动态生成大量样式字符串。这使得它在首屏加载速度(FCP)和吞吐量上通常表现最佳,特别是在 Next.js 环境中。

// styled-jsx SSR 输出示意
// 服务端只输出 HTML 和简单的 class 引用,CSS 已提取
<div class="jsx-123456789">Content</div>

emotion 和 styled-components 都需要在服务端收集样式(Style Collection),然后将完整的 CSS 字符串注入到 HTML 的 <head> 中。虽然两者都做了大量优化,但 emotion 通常在基准测试中表现出更低的内存占用和更快的序列化速度,特别是在处理大量动态样式时。

// emotion SSR 配置示意
import createCache from '@emotion/cache';
import { CacheProvider } from '@emotion/react';

// 服务端需要手动创建 cache 并收集样式
const cache = createCache({ key: 'css' });
// ...渲染逻辑...
// 提取 cache.sheet.tags 注入 HTML

🔄 动态样式处理能力

当样式需要根据 props 频繁变化时,各家的表现不同。

styled-components 和 emotion 都非常擅长处理动态样式。它们会根据 props 的变化重新计算样式并生成新的类名。emotion 的对象语法在处理复杂条件逻辑时往往比模板字符串更简洁。

// styled-components: 动态 Props
const Box = styled.div`background: ${props => props.active ? 'green' : 'red'};`;

// emotion: 动态对象
function Box({ active }) {
  return <div css={{ background: active ? 'green' : 'red' }} />;
}

styled-jsx 处理动态样式相对笨重。虽然支持在模板字符串中插值,但每次 props 变化可能导致整个 <style> 块重新计算或注入,且无法像前两者那样细粒度地生成类名。对于高度动态的 UI(如拖拽、实时主题切换),它可能不是最佳选择。

// styled-jsx: 动态插值(相对受限)
function Box({ active }) {
  return (
    <div>
      <style jsx>{`
        div { background: ${active ? 'green' : 'red'}; }
      `}</style>
    </div>
  );
}

🤝 共同点:它们解决了什么?

尽管实现不同,这三个活跃的库都解决了 CSS 的核心痛点:

1. 样式隔离(Scoped Styles)

所有方案都确保样式只作用于当前组件,避免全局污染。

// 所有库都能实现:组件内的 .title 不会影响外部的 .title
// Emotion/SC: 生成唯一类名 css-12345
// Styled-JSX: 生成唯一属性选择器 [jsx-12345]

2. 主题支持(Theming)

都提供了 ThemeProvider 机制,允许在组件树深处访问全局主题变量。

// Emotion / Styled-Components
const Button = styled.button`color: ${props => props.theme.primary};`;

// Styled-JSX
import { useTheme } from 'styled-jsx';
function Button() {
  const theme = useTheme();
  return <style jsx>{`button { color: ${theme.primary}; }`}</style>;
}

3. 关键 CSS 提取(Critical CSS)

都支持 SSR 时的关键 CSS 提取,确保首屏样式不闪烁。

📊 总结对比表

特性emotionstyled-componentsstyled-jsxglamorous
状态✅ 活跃维护✅ 活跃维护✅ 活跃维护 (Next.js 专用)❌ 已废弃
核心机制运行时注入运行时注入构建时提取运行时注入
语法风格对象 + 模板字符串模板字符串组件内 <style> 标签对象 + HOC
运行时开销低中极低 (接近 0)中
动态样式⭐⭐⭐⭐⭐ 极强⭐⭐⭐⭐⭐ 极强⭐⭐⭐ 一般⭐⭐⭐⭐ 强
Next.js 集成优秀 (需配置)优秀 (需配置)原生内置 (零配置)不支持
推荐场景复杂动态应用、非 Next 项目标准 React 应用、生态依赖重Next.js 项目、追求极致性能无 (请迁移)

💡 架构师的建议

选择哪个库,本质上是在灵活性和性能之间做权衡,同时考虑你的技术栈。

  1. 如果你在构建 Next.js 应用:首选 styled-jsx。它是框架的一部分,无需额外配置,性能最优,能最大程度发挥 Next.js 的静态生成和增量渲染优势。除非你有极其复杂的动态样式需求,否则不要舍近求远。

  2. 如果你在构建通用的 React 应用(Vite, CRA, Remix 等):emotion 是目前的最佳平衡点。它比 styled-components 更轻量,API 更灵活(对象语法对 TS 更友好),且性能略优。它是许多现代 UI 库(如 Chakra UI, Mantine)的底层引擎。

  3. 如果你依赖庞大的现有生态或团队习惯:styled-components 依然可靠。如果你的团队已经非常熟悉模板字符串语法,或者你使用的 UI 库强依赖它,继续使用它完全没有问题。它的社区资源是最丰富的。

  4. 绝对不要选:glamorous。它的时代已经结束,继续投入时间是技术债务的累积。

最终,没有银弹。但在 2024 年的技术视野下,emotion 提供了最稳健的通用解决方案,而 styled-jsx 则是 Next.js 领域的王者。

如何選擇: styled-jsx vs emotion vs glamorous vs styled-components

  • styled-jsx:

    如果你正在使用 Next.js 构建应用,且追求最小的打包体积和最快的首屏加载速度,选择 styled-jsx。它是 Next.js 的一等公民,利用构建时提取 CSS 的技术消除了运行时解析开销,但牺牲了部分动态样式的灵活性,不适合需要复杂运行时样式计算的场景。

  • emotion:

    如果你的项目需要极致的运行时性能、复杂的动态样式逻辑,或者需要在非 Next.js 环境中进行灵活的服务端渲染,选择 emotion。它的 API 既支持标签模板也支持对象语法,适合大型应用中对样式系统有高度定制需求的团队。

  • glamorous:

    切勿在新项目中选择 glamorous。该库已官方宣布停止维护并标记为废弃。其核心功能已被 emotion 吸收,继续使用该库将面临安全漏洞无法修复和缺乏新特性支持的风险。现有项目应尽快迁移至 emotion。

  • styled-components:

    如果你偏好“样式即组件”的开发体验,希望拥有最丰富的社区插件、教程和第三方工具支持,选择 styled-components。它非常适合标准 Create React App 项目或需要大量现成主题 UI 库集成的场景,尽管其运行时开销略高于 emotion。

styled-jsx 的 README

styled-jsx

build status

Full, scoped and component-friendly CSS support for JSX (rendered on the server or the client).

Code and docs are for v3 which we highly recommend you to try. Looking for styled-jsx v2? Switch to the v2 branch.

Getting started

Firstly, install the package:

npm install --save styled-jsx

Next, add styled-jsx/babel to plugins in your babel configuration:

{
  "plugins": ["styled-jsx/babel"]
}

Now add <style jsx> to your code and fill it with CSS:

export default () => (
  <div>
    <p>only this paragraph will get the style :)</p>

    {/* you can include <Component />s here that include
         other <p>s that don't get unexpected styles! */}

    <style jsx>{`
      p {
        color: red;
      }
    `}</style>
  </div>
)

Configuration options

The following are optional settings for the babel plugin.

optimizeForSpeed

Blazing fast and optimized CSS rules injection system based on the CSSOM APIs.

{
  "plugins": [["styled-jsx/babel", { "optimizeForSpeed": true }]]
}

When in production* this mode is automatically enabled.
Beware that when using this option source maps cannot be generated and styles cannot be edited via the devtools.

* process.env.NODE_ENV === 'production'

sourceMaps

Generates source maps (default: false)

styleModule

Module that the transpiled files should import (default: styled-jsx/style)

vendorPrefixes

Turn on/off automatic vendor prefixing (default: true)

Features

  • Full CSS support, no tradeoffs in power
  • Runtime size of just 3kb (gzipped, from 12kb)
  • Complete isolation: Selectors, animations, keyframes
  • Built-in CSS vendor prefixing
  • Very fast, minimal and efficient transpilation (see below)
  • High-performance runtime-CSS-injection when not server-rendering
  • Future-proof: Equivalent to server-renderable "Shadow CSS"
  • Source maps support
  • Dynamic styles and themes support
  • CSS Preprocessing via Plugins

Using in Next.js

Next.js automatically configures styled-jsx with babel or swc, you don't have to configure it manually.

How It Works

The example above transpiles to the following:

import _JSXStyle from 'styled-jsx/style'

export default () => (
  <div className="jsx-123">
    <p className="jsx-123">only this paragraph will get the style :)</p>
    <_JSXStyle id="123">{`p.jsx-123 {color: red;}`}</_JSXStyle>
  </div>
)

Why It Works Like This

Unique classnames give us style encapsulation and _JSXStyle is heavily optimized for:

  • Injecting styles upon render
  • Only injecting a certain component's style once (even if the component is included multiple times)
  • Removing unused styles
  • Keeping track of styles for server-side rendering

Targeting The Root

Notice that the outer <div> from the example above also gets a jsx-123 classname. We do this so that you can target the "root" element, in the same manner that :host works with Shadow DOM.

If you want to target only the host, we suggest you use a class:

export default () => (
  <div className="root">
    <style jsx>{`
      .root {
        color: green;
      }
    `}</style>
  </div>
)

Global styles

To skip scoping entirely, you can make the global-ness of your styles explicit by adding global.

export default () => (
  <div>
    <style jsx global>{`
      body {
        background: red;
      }
    `}</style>
  </div>
)

The advantage of using this over <style> is twofold: no need to use dangerouslySetInnerHTML to avoid escaping issues with CSS and take advantage of styled-jsx's de-duping system to avoid the global styles being inserted multiple times.

One-off global selectors

Sometimes it's useful to skip selectors scoping. In order to get a one-off global selector we support :global(), inspired by css-modules.

This is very useful in order to, for example, generate a global class that you can pass to 3rd-party components. For example, to style react-select which supports passing a custom class via optionClassName:

import Select from 'react-select'
export default () => (
  <div>
    <Select optionClassName="react-select" />

    <style jsx>{`
      /* "div" will be prefixed, but ".react-select" won't */

      div :global(.react-select) {
        color: red;
      }
    `}</style>
  </div>
)

Dynamic styles

To make a component's visual representation customizable from the outside world there are three options.

Via interpolated dynamic props

Any value that comes from the component's render method scope is treated as dynamic. This makes it possible to use props and state for example.

const Button = props => (
  <button>
    {props.children}
    <style jsx>{`
      button {
        padding: ${'large' in props ? '50' : '20'}px;
        background: ${props.theme.background};
        color: #999;
        display: inline-block;
        font-size: 1em;
      }
    `}</style>
  </button>
)

New styles' injection is optimized to perform well at runtime.

That said when your CSS is mostly static we recommend to split it up in static and dynamic styles and use two separate style tags so that, when changing, only the dynamic parts are recomputed/rendered.

const Button = props => (
  <button>
    {props.children}
    <style jsx>{`
      button {
        color: #999;
        display: inline-block;
        font-size: 2em;
      }
    `}</style>
    <style jsx>{`
      button {
        padding: ${'large' in props ? '50' : '20'}px;
        background: ${props.theme.background};
      }
    `}</style>
  </button>
)

Via className toggling

The second option is to pass properties that toggle class names.

const Button = props => (
  <button className={'large' in props && 'large'}>
    {props.children}
    <style jsx>{`
      button {
        padding: 20px;
        background: #eee;
        color: #999;
      }
      .large {
        padding: 50px;
      }
    `}</style>
  </button>
)

Then you would use this component as either <Button>Hi</Button> or <Button large>Big</Button>.

Via inline style

*best for animations

Imagine that you wanted to make the padding in the button above completely customizable. You can override the CSS you configure via inline-styles:

const Button = ({ padding, children }) => (
  <button style={{ padding }}>
    {children}
    <style jsx>{`
      button {
        padding: 20px;
        background: #eee;
        color: #999;
      }
    `}</style>
  </button>
)

In this example, the padding defaults to the one set in <style> (20), but the user can pass a custom one via <Button padding={30}>.

Constants

It is possible to use constants like so:

import { colors, spacing } from '../theme'
import { invertColor } from '../theme/utils'

const Button = ({ children }) => (
  <button>
    {children}
    <style jsx>{`
      button {
        padding: ${spacing.medium};
        background: ${colors.primary};
        color: ${invertColor(colors.primary)};
      }
    `}</style>
  </button>
)

Please keep in mind that constants defined outside of the component scope are treated as static styles.

Server-Side Rendering

styled-jsx v5 introduced StyledRegistry component and useStyleRegistry hook to let you scope styles rendering in each SSR render to keep concurrent-safe.

  • registry.styles() will return the array of react components for style tags.
  • registry.flush() can clean the existing styles in the registry, it's optional for SSR when you have a standalone registry for each SSR render.

Next.js 12 integrates with styled-jsx v5 and manages the registry for you.

import React from 'react'
import ReactDOM from 'react-dom/server'
import { StyleRegistry, useStyleRegistry } from 'styled-jsx'
import App from './app'

function Styles() {
  const registry = useStyleRegistry()
  const styles = registry.styles()
  return <>{styles}</>
}

export default (req, res) => {
  const app = ReactDOM.renderToString(<App />)
  const html = ReactDOM.renderToStaticMarkup(
    <StyleRegistry>
      <html>
        <head>
          <Styles />
        </head>
        <body>
          <div id="root" dangerouslySetInnerHTML={{ __html: app }} />
        </body>
      </html>
    </StyleRegistry>
  )
  res.end('<!doctype html>' + html)
}

There's also a new API createStyleRegistry that is introduced when you have to create a registry manually. In this way you can operate the registry yourself to extract the rendered styles (registry.styles()) or flush them out (registry.flush()).

const registry = createStyleRegistry()
const styles = registry.styles() // access styles

function Page() {
  return (
    <StyleRegistry registry={registry}>
      <App />
    </StyleRegistry>
  )
}

By default <StyleRegistry /> will use the registry from root top StyleRegistry, which means there's only one registry in the react tree.

It's paramount that you use one of these two functions so that the generated styles can be diffed when the client loads and duplicate styles are avoided.

Content Security Policy

Strict CSP is supported.

You should generate a nonce per request.

import nanoid from 'nanoid'

const nonce = Buffer.from(nanoid()).toString('base64') //ex: N2M0MDhkN2EtMmRkYi00MTExLWFhM2YtNDhkNTc4NGJhMjA3

You must then pass a nonce to registry.styles({ nonce }) and set a <meta property="csp-nonce" content={nonce} /> tag.

Your CSP policy must share the same nonce as well (the header nonce needs to match the html nonce and remain unpredictable). Content-Security-Policy: default-src 'self'; style-src 'self' 'nonce-N2M0MDhkN2EtMmRkYi00MTExLWFhM2YtNDhkNTc4NGJhMjA3';

External CSS and styles outside of the component

In styled-jsx styles can be defined outside of the component's render method or in separate JavaScript modules using the styled-jsx/css library. styled-jsx/css exports three tags that can be used to tag your styles:

  • css, the default export, to define scoped styles.
  • css.global to define global styles.
  • css.resolve to define scoped styles that resolve to the scoped className and a styles element.

External styles

In an external file:

/* styles.js */
import css from 'styled-jsx/css'

// Scoped styles
export const button = css`
  button {
    color: hotpink;
  }
`

// Global styles
export const body = css.global`body { margin: 0; }`

// Resolved styles
export const link = css.resolve`a { color: green; }`
// link.className -> scoped className to apply to `a` elements e.g. jsx-123
// link.styles -> styles element to render inside of your component

// Works also with default exports
export default css`
  div {
    color: green;
  }
`

You can then import and use those styles:

import styles, { button, body } from './styles'

export default () => (
  <div>
    <button>styled-jsx</button>
    <style jsx>{styles}</style>
    <style jsx>{button}</style>
    <style jsx global>
      {body}
    </style>
  </div>
)

N.B. All the tags except for resolve don't support dynamic styles.

resolve and global can also be imported individually:

import { resolve } from 'styled-jsx/css'
import { global } from 'styled-jsx/css'

If you use Prettier we recommend you to use the default css export syntax since the tool doesn't support named imports.

Styles outside of components

The css tag from styled-jsx/css can be also used to define styles in your components files but outside of the component itself. This might help with keeping render methods smaller.

import css from 'styled-jsx/css'

export default () => (
  <div>
    <button>styled-jsx</button>
    <style jsx>{button}</style>
  </div>
)

const button = css`
  button {
    color: hotpink;
  }
`

Like in externals styles css doesn't work with dynamic styles. If you have dynamic parts you might want to place them inline inside of your component using a regular <style jsx> element.

The resolve tag

The resolve tag from styled-jsx/css can be used when you need to scope some CSS - for example, if you need to style nested components from the parent, such as the Link component in the example below.

It works by returning the generated scoped className and related styles.

import React from 'react'
import Link from 'some-library'

import css from 'styled-jsx/css'

const { className, styles } = css.resolve`
  a { color: green }
`

export default () => (
  <div>
    {/* use the className */}
    <Link className={className}>About</Link>

    {/* render the styles for it */}
    {styles}
  </div>
)

The resolve tag also supports dynamic styles, via template string interpolation:

import React from 'react'
import css from 'styled-jsx/css'

function getLinkStyles(color) {
  return css.resolve`
    a { color: ${color} }
  `
}

export default props => {
  const { className, styles } = getLinkStyles(props.theme.color)

  return (
    <div>
      <Link className={className}>About</Link>
      {styles}
    </div>
  )
}

Using resolve as a Babel macro

If you can't (or would rather not) make changes to your .babelrc, the resolve tag can be used as a Babel macro, thanks to the babel-plugin-macros system.

To set this up, first of all, install styled-jsx and babel-plugin-macros:

npm i --save styled-jsx
npm i --save-dev babel-plugin-macros

Next, add babel-plugin-macros to your Babel configuration:

{
  "plugins": ["babel-plugin-macros"]
}

You can then use resolve by importing it from styled-jsx/macro.

import css from 'styled-jsx/macro'

const { className, styles } = css.resolve`
  a { color: green }
`

export default () => (
  <div>
    <Link className={className}>About</Link>
    {styles}
  </div>
)
Usage with create-react-app

Create React App comes with babel-plugin-macros already installed, so the only thing that needs to be done is to install styled-jsx:

npm i --save styled-jsx

Then resolve can be imported from styled-jsx/macro and used the same way as in the example in the Using resolve as a Babel macro section above.

Styles in regular CSS files

styled-jsx v3 comes with a webpack loader that lets you write styles in regular css files and consume them in React.

import styles from '../components/button/styles.css'

export default () => (
  <div>
    <button>styled-jsx</button>
    <style jsx>{styles}</style>
  </div>
)

To consume the styles in your component you can import them from your CSS file and render them using a <style jsx> tag. Remember to add the global prop if you want your styles to be global.

To use this feature you need to register the loader in your webpack config file, before babel-loader which will then transpile the styles via styled-jsx/babel

config: {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: require('styled-jsx/webpack').loader,
            options: {
              type: 'scoped'
            }
          }
        ]
      }
    ]
  }
}

The plugin accepts a type option to configure whether the styles should be scoped, global or resolve (see above). By default its values is set to scoped. type can also be a function which takes the fileName and the fileNameQuery that is being transpiled and must return a valid type.

type validTypes = 'scoped' | 'global' | 'resolve'
type fileName = string
type Options = {|
  type: validTypes | ((fileName, options) => validTypes)
|}
import styles from './styles.css?type=global'

// webpack
config: {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: require('styled-jsx/webpack').loader,
            options: {
              type: (fileName, options) => options.query.type || 'scoped'
            }
          }
        ]
      }
    ]
  }
}

The type can also be set per individual CSS file via CSS comment:

/* @styled-jsx=scoped */

button {
  color: red;
}

The CSS comment option will override the one in the webpack configuration only for this specific file.

Next.js

Example of next.config.js to integrate styled-jsx/webpack:

module.exports = {
  webpack: (config, { defaultLoaders }) => {
    config.module.rules.push({
      test: /\.css$/,
      use: [
        defaultLoaders.babel,
        {
          loader: require('styled-jsx/webpack').loader,
          options: {
            type: 'scoped'
          }
        }
      ]
    })

    return config
  }
}

CSS Preprocessing via Plugins

Styles can be preprocessed via plugins.

Plugins are regular JavaScript modules that export a simple function with the following signature:

function plugin(css: string, options: Object): string

Basically they accept a CSS string in input, optionally modify it and finally return it.

Plugins make it possible to use popular preprocessors like SASS, Less, Stylus, PostCSS or apply custom transformations to the styles at compile time.

To register a plugin add an option plugins for styled-jsx/babel to your .babelrc. plugins must be an array of module names or full paths for local plugins.

{
  "plugins": [
    [
      "styled-jsx/babel",
      {
        "plugins": [
          "my-styled-jsx-plugin-package",
          "/full/path/to/local/plugin"
        ]
      }
    ]
  ]
}
Instructions to integrate with Next.js In order to register styled-jsx plugins in a Next.js app you need to create a custom .babelrc file:
{
  "presets": [
    [
      "next/babel",
      {
        "styled-jsx": {
          "plugins": ["styled-jsx-plugin-postcss"]
        }
      }
    ]
  ]
}

This is a fairly new feature so make sure that you using a version of Next.js that supports passing options to styled-jsx.


Plugins are applied in definition order left to right before styles are scoped.

In order to resolve local plugins paths you can use NodeJS' require.resolve.

N.B. when applying the plugins styled-jsx replaces template literals expressions with placeholders because otherwise CSS parsers would get invalid CSS E.g.

/* `ExprNumber` is a number */
%%styled-jsx-placeholder-ExprNumber%%

Plugins won't transform expressions (eg. dynamic styles).

When publishing a plugin you may want to add the keywords: styled-jsx and styled-jsx-plugin. We also encourage you to use the following naming convention for your plugins:

styled-jsx-plugin-<your-plugin-name>

Plugin options

Users can set plugin options by registering a plugin as an array that contains the plugin path and an options object.

{
  "plugins": [
    [
      "styled-jsx/babel",
      {
        "plugins": [
          ["my-styled-jsx-plugin-package", { "exampleOption": true }]
        ],
        "sourceMaps": true
      }
    ]
  ]
}

Each plugin receives a options object as second argument which contains the babel and user options:

;(css, options) => {
  /* ... */
}

The options object has the following shape:

{
  // user options go here
  // eg. exampleOption: true

  // babel options
  babel: {
    sourceMaps: boolean,
    vendorPrefixes: boolean,
    isGlobal: boolean,
    filename: ?string, // defined only when the filename option is passed to Babel, such as when using Babel CLI or Webpack
    location: { // the original location of the CSS block in the JavaScript file
      start: {
        line: number,
        column: number,
      },
      end: {
        line: number,
        column: number,
      }
    }
  }
}

Example plugins

The following plugins are proof of concepts/sample:

Rendering in tests

If you're using a tool such as Enzyme, you might want to avoid compiling your styles in test renders. In general, styled-jsx artifacts like jsx-123 classnames and vendor prefixing are not direct concerns of your component, and they generate a lot of snapshot noise.

One option is to exclude the styled-jsx/babel plugin from the test environment using env in your Babel config (see Config Merging options).

But this can cause noise in your terminal output when rendering:

   console.error node_modules/react-dom/cjs/react-dom.development.js:527
      Warning: Received `true` for a non-boolean attribute `jsx`.

The styled-jsx/babel-test solves this problem. It simply strips jsx attributes from all <style> tags. Be sure to target each environment with the appropriate plugin:

{
  "env": {
    "production": {
      "plugins": ["styled-jsx/babel"]
    },
    "development": {
      "plugins": ["styled-jsx/babel"]
    },
    "test": {
      "plugins": ["styled-jsx/babel-test"]
    }
  }
}

styled-jsx/css in tests

When using styled-jsx/babel-test, styled-jsx/css throws the following error:

styled-jsx/css: if you are getting this error it means that your `css` tagged template literals were not transpiled.

to solve this issue you need to mock styled-jsx/css. You can find a guide at the following link https://kevinjalbert.com/jest-snapshots-reducing-styled-jsx-noise/

FAQ

Warning: unknown jsx prop on <style> tag

If you get this warning it means that your styles were not compiled by styled-jsx.

Please take a look at your setup and make sure that everything is correct and that the styled-jsx transformation is ran by Babel.

Can I return an array of components when using React 16?

No, this feature is not supported. However we support React Fragments, which are available in React 16.2.0 and above.

const StyledImage = ({ src, alt = '' }) => (
  <React.Fragment>
    <img src={src} alt={alt} />
    <style jsx>{`
      img {
        max-width: 100%;
      }
    `}</style>
  </React.Fragment>
)

Styling third parties / child components from the parent

When the component accepts a className (or ad-hoc) prop as a way to allow customizations then you can use the resolve tag from styled-jsx/css.

When the component doesn't accept any className or doesn't expose any API to customize the component, then your only option is to use :global() styles:

export default () => (
  <div>
    <ExternalComponent />

    <style jsx>{`
      /* "div" will be prefixed, but ".nested-element" won't */

      div > :global(.nested-element) {
        color: red;
      }
    `}</style>
  </div>
)

Please keep in mind that :global() styles will affect the entire subtree, so in many cases you may want to be careful and use the children (direct descendant) selector >.

Build a component library with styled-jsx

There's an article explaining how to bundle React components with Rollup and styled-jsx as an external dependency.

Syntax Highlighting

When working with template literals a common drawback is missing syntax highlighting. The following editors currently have support for highlighting CSS inside <style jsx> elements.

If you have a solution for an editor not on the list please open a PR and let us now.

Atom

The language-babel package for the Atom editor has an option to extend the grammar for JavaScript tagged template literals.

After installing the package add the code below to the appropriate settings entry. In a few moments you should be blessed with proper CSS syntax highlighting. (source)

"(?<=<style jsx>{)|(?<=<style jsx global>{)|(?<=css)":source.css.styled

babel-language settings entry

Webstorm/Idea

The IDE let you inject any language in place with Inject language or reference in an Intention Actions (default alt+enter). Simply perform the action in the string template and select CSS. You get full CSS highlighting and autocompletion and it will last until you close the IDE.

Additionally you can use language injection comments to enable all the IDE language features indefinitely using the language comment style:

import { colors, spacing } from '../theme'
import { invertColor } from '../theme/utils'

const Button = ({ children }) => (
  <button>
    {children}

    {/*language=CSS*/}
    <style jsx>{`
      button {
        padding: ${spacing.medium};
        background: ${colors.primary};
        color: ${invertColor(colors.primary)};
      }
    `}</style>
  </button>
)

Emmet

If you're using Emmet you can add the following snippet to ~/emmet/snippets-styledjsx.json This will allow you to expand style-jsx to a styled-jsx block.

{
  "html": {
    "snippets": {
      "style-jsx": "<style jsx>{`\n\t$1\n`}</style>"
    }
  }
}

Syntax Highlighting Visual Studio Code Extension

Launch VS Code Quick Open (⌘+P), paste the following command, and press enter.

ext install Divlo.vscode-styled-jsx-syntax

If you use Stylus instead of plain CSS, install vscode-styled-jsx-stylus or paste the command below.

ext install vscode-styled-jsx-stylus

Autocomplete Visual Studio Code Extension

Launch VS Code Quick Open (⌘+P), paste the following command, and press enter.

ext install Divlo.vscode-styled-jsx-languageserver

Vim

Install vim-styled-jsx with your plugin manager of choice.

ESLint

If you're using eslint-plugin-import, the css import will generate errors, being that it's a "magic" import (not listed in package.json). To avoid these, simply add the following line to your eslint configuration:

"settings": {"import/core-modules": ["styled-jsx/css"] }

TypeScript

If you're using TypeScript, then in order to allow <style jsx> tags to be properly understood by it, create a file named "styled-jsx.d.ts" anywhere within your project containing the following, or add this line to the top of any single existing .ts file within your project:

/// <reference types="styled-jsx" />

If you're using babel to transform styled-jsx code with TypeScript, you need to specify "jsx": "preserve" in your tsconfig.json to keep the original JSX and let babel parse and transform with styled-jsx babel plugin.

Credits

  • Pedram Emrouznejad (rijs) suggested attribute selectors over my initial class prefixing idea.
  • Sunil Pai (glamor) inspired the use of murmurhash2 (minimal and fast hashing) and an efficient style injection logic.
  • Sultan Tarimo built stylis.js, a super fast and tiny CSS parser and compiler.
  • Max Stoiber (styled-components) proved the value of retaining the familiarity of CSS syntax and pointed me to the very efficient stylis compiler (which we forked to very efficiently append attribute selectors to the user's css)
  • Yehuda Katz (ember) convinced me on Twitter to transpile CSS as an alternative to CSS-in-JS.
  • Evan You (vuejs) discussed his Vue.js CSS transformation with me.
  • Henry Zhu (babel) helpfully pointed me to some important areas of the babel plugin API.

Authors