Skip to Content
vitus·labs
Migrating

From Emotion

Adopt Vitus Labs in an Emotion app. Keep Emotion through its connector, or switch to @vitus-labs/styler.

You can bring Vitus Labs into an Emotion codebase in two ways:

Option A: keep EmotionOption B: switch to styler
Your existing componentsUnchanged (including css prop and object styles)Rewritten to tagged templates where needed
Vitus components (elements, rocketstyle, coolgrid, …)Render through @emotion/styledRender through @vitus-labs/styler
SSR setupUnchangedRemoved: React 19 <style precedence> handles it
CSS engine in the bundle@emotion/react + @emotion/styled (16.59 KB min+gz)styler (6.98 KB min+gz)

Sizes are minified + gzipped with React external (from the styler bundle-size table).

Styler only accepts tagged-template CSS. If your codebase relies heavily on object styles or the css prop, Option A is much less work. Option B means rewriting those parts.

Option A: keep Emotion

All Vitus packages go through @vitus-labs/core's engine interface, not a specific CSS-in-JS library. @vitus-labs/connector-emotion adapts Emotion to that interface.

1. Check versions

The connector's peer dependencies are @emotion/react >= 11, @emotion/styled >= 11 and react >= 19. You also need @vitus-labs/core for init().

2. Install

npm install @vitus-labs/core @vitus-labs/connector-emotion

Then add the Vitus packages you want, for example @vitus-labs/elements @vitus-labs/unistyle @vitus-labs/rocketstyle. @vitus-labs/styler is not needed: the Vitus packages only list it as a dev dependency.

3. Call init() before anything renders

src/init.ts
import { init } from '@vitus-labs/core'
import * as connector from '@vitus-labs/connector-emotion'

init({
  ...connector,
  component: 'div',
  textComponent: 'span',
})

The connector has named exports only (no default export), so use a namespace import:

ExportWhat it is
styled@emotion/styled, re-exported
keyframes, useTheme@emotion/react, re-exported
providerEmotion's ThemeProvider
cssAn adapter, not Emotion's css. It returns a plain string for static templates and a (props) => … function for dynamic ones, so Vitus' styled-components-style composition works inside @emotion/styled
createGlobalStyleA component wrapping Emotion's <Global>, matching the styled-components API. It injects the context theme for ({ theme }) => … interpolations (an explicit theme prop wins)

Import this file once at the top of your entry point.

4. Provide the theme through a Vitus Provider

The Vitus Provider (from @vitus-labs/core, @vitus-labs/unistyle or @vitus-labs/rocketstyle) fills the internal Vitus context and renders Emotion's ThemeProvider with the same theme. Swap your Emotion ThemeProvider for it and pass one theme with both sets of keys:

src/App.tsx
import { Provider } from '@vitus-labs/rocketstyle'

const theme = {
  rootSize: 16,
  breakpoints: { xs: 0, sm: 576, md: 768, lg: 992, xl: 1200 },
  // your existing Emotion theme keys
  colors: { primary: '#0d6efd', text: '#212529' },
}

export const App = () => (
  <Provider theme={theme} mode="light">
    {/* existing Emotion components see the theme as before */}
    <Routes />
  </Provider>
)

5. Keep your SSR setup

Vitus components now go through @emotion/styled, so whatever SSR setup you have (Emotion's default inline style tags, or CacheProvider + @emotion/server) covers them too.

Caveats

  • Keep importing css from @emotion/react in your own code. The connector's css is the adapter described above. It returns a string or a function, so it isn't a drop-in replacement for Emotion's SerializedStyles (e.g. in the css prop).
  • keyframes inside Vitus css: the adapter keeps Emotion style objects (such as keyframes results) as objects and serializes them through Emotion's own css, so animation: ${fadeIn} 1s works.
  • No useCSS. Emotion only inserts a rule when it passes through @emotion/styled or <Global>, so the connector doesn't export useCSS. No Vitus package needs it.
  • Types: the connector does not augment core's CSSEngineResult, because css returns a string or a function and interface merging can't describe that.

See Connectors for the full interface and how init() works.

Option B: switch to styler

@vitus-labs/styler covers the template-literal half of Emotion: styled.tag, css`…`, keyframes, ThemeProvider, useTheme, as, shouldForwardProp and component selectors. It does not cover the object-style or css-prop half.

What isn't supported

Checked against the styler source:

  • Object styles. styled and css are tagged templates only. styled.div({ color: 'red' }), styled.div((p) => ({ … })) and css({ … }) don't work, and a plain object interpolated into a template is stringified (it is not converted to CSS).
  • The css prop (jsxImportSource: '@emotion/react' / the jsx pragma). Use styled, or useCSS() + className.
  • cx, ClassNames, withTheme, Global (use createGlobalStyle), withEmotionCache.
  • CacheProvider / createCache options: key, nonce, prepend and stylisPlugins (e.g. RTL) have no equivalent. Class names always use the vl- prefix, and there is no plugin pipeline or vendor prefixing.
  • styled options other than shouldForwardProp: label and target aren't supported. Styler has its own boost option.
  • styled.div<Props> generics: styler's styled isn't generic. Drop the type argument (interpolation props are typed loosely).

API mapping

Emotion@vitus-labs/stylerNotes
import styled from '@emotion/styled'import { styled } from '@vitus-labs/styler'Named export only
styled.div`…`, styled(Comp)`…`SameA wrapped component receives className
css`…` from @emotion/react (composed into styled)css`…`Returns a lazy CSSResult; nest it in styled or other css
css`…` from @emotion/css (returns a class name)useCSS(template, props?)A hook, so call it inside a component
<Global styles={…} />createGlobalStyle`…` → <GlobalStyles />Mount-scoped and ref-counted
keyframes`…`SameTagged template only (no object form), no dynamic interpolations
ThemeProviderSameObject themes replace the outer theme (Emotion merges them); use a function theme to extend
useTheme()SameReturns {} outside a provider
withTheme(Comp)Not providedCall useTheme() inside the component
as propSameNever forwarded to the element
$-prefixed propsTransientStyler never forwards $ props, not even to wrapped components
styled('div', { shouldForwardProp })Same signatureOn a DOM tag the custom filter replaces the built-in HTML/SVG filter. Emotion's default filter is @emotion/is-prop-valid; styler uses its own allowlist
${Child} component selector (needs @emotion/babel-plugin)Same, no plugin, static components onlyA dynamic styled component throws [styler] … cannot be a selector (needs a static template)
styled(StyledComp)SameFolded into one component; the extension wins
CacheProvider, @emotion/server (extractCritical, extractCriticalToChunks, createEmotionServer)Not needed / not providedSSR is automatic with React 19 <style precedence>
declare module '@emotion/react' { interface Theme }declare module '@vitus-labs/styler' { interface DefaultTheme }Same augmentation pattern

Step-by-step

1. Install and re-point Vitus packages

npm install @vitus-labs/styler @vitus-labs/core @vitus-labs/connector-styler
src/init.ts
  import { init } from '@vitus-labs/core'
- import * as connector from '@vitus-labs/connector-emotion'
+ import * as connector from '@vitus-labs/connector-styler'

  init({ ...connector, component: 'div', textComponent: 'span' })

@vitus-labs/styler peer-depends on @vitus-labs/core and react >= 19.

2. Replace imports

- import styled from '@emotion/styled'
- import { css, keyframes, ThemeProvider, useTheme } from '@emotion/react'
+ import { styled, css, keyframes, ThemeProvider, useTheme } from '@vitus-labs/styler'

3. Convert object styles to templates

- const Card = styled.div((p) => ({
-   padding: 16,
-   color: p.theme.colors.text,
-   '&:hover': { opacity: 0.8 },
- }))
+ const Card = styled.div`
+   padding: 16px;
+   color: ${(p) => p.theme.colors.text};
+   &:hover { opacity: 0.8; }
+ `

Numbers are not turned into px, so write units explicitly.

4. Replace the css prop

- <div css={css`display: flex; gap: 8px;`}>…</div>
+ const Row = styled.div`display: flex; gap: 8px;`
+ <Row>…</Row>

Or, without a wrapper component:

import { css, useCSS } from '@vitus-labs/styler'

const row = css`display: flex; gap: 8px;`

function Toolbar({ children }) {
  const className = useCSS(row)
  return <div className={className}>{children}</div>
}

useCSS emits no CSS on the server (there's no element to carry a <style precedence> tag). The rules are injected on hydration, so use styled for markup that must be styled in the server HTML.

Then remove jsxImportSource: '@emotion/react' from tsconfig.json / your Babel or SWC config, any /** @jsxImportSource @emotion/react */ pragmas, and @emotion/babel-plugin.

5. Replace <Global>

- <Global styles={css`body { margin: 0; }`} />
+ const GlobalStyles = createGlobalStyle`body { margin: 0; }`
+ <GlobalStyles />

Rules are inserted when the first instance mounts and removed when the last one unmounts. A dynamic global whose value changes (e.g. a light/dark toggle) replaces its previous rules.

6. Remove the SSR plumbing

On the server, styled components render a <style href precedence="medium"> next to their output (global styles use "low"). React 19 hoists, dedupes and orders those tags. Delete CacheProvider / createCache, @emotion/server calls, and any Next.js App Router registry built on useServerInsertedHTML. Referenced @keyframes are shipped inside the same <style precedence> tag, so animations work in SSR HTML. On hydration styler reads those tags, so rules aren't injected twice.

You do not need a per-request createSheet() on this default path. createSheet() is for the manual SSR mode, meant for runtimes that don't process <style precedence>.

7. Fix theme usage

  • Nested providers: Emotion merges a nested object theme into the outer one; styler replaces it. Turn partial nested themes into functions, defined outside render:

    const withAccent = (outer) => ({ ...outer, colors: { ...outer.colors, primary: '#d63384' } })
    
    <ThemeProvider theme={withAccent}>…</ThemeProvider>
  • withTheme → useTheme().

  • Components wrapped with styled(MyComponent) that read props.theme → useTheme(). Styler resolves interpolations with the context theme but doesn't pass it on to a wrapped component (an explicit theme prop is still forwarded).

  • Type augmentation: replace declare module '@emotion/react' { interface Theme … } with declare module '@vitus-labs/styler' { interface DefaultTheme … }.

  • If you use Vitus components, keep using the Vitus Provider from Option A, step 4. Through connector-styler it renders styler's ThemeProvider.

8. Check shouldForwardProp and $ props

  • A custom shouldForwardProp on a DOM tag decides alone. If yours was (prop) => isPropValid(prop) && prop !== 'x', that still works. If it was only prop !== 'x', unknown props now reach the DOM. Prefer $ props, which never need a filter.
  • Styler strips $ props even when wrapping a custom component. If a wrapped component expects a $-prefixed prop, rename it.

9. Check component selectors and extensions

  • ${Child} works without the Babel plugin, but only when Child has no function interpolations. A dynamic target throws at creation time. Make it static, or target it with a class or data-* attribute.
  • styled(StyledComponent) folds base and extension into one component and one rule. The extension's declarations always win, $ props reach the base's interpolations, and ${Base} selectors still match the extension.

10. Clean up

  • Nesting is passed to the browser as native CSS nesting (no stylis). &:hover, & h2, &.active work. Sass-style suffix concatenation (&-icon) does not. @media / @supports / @container inside a rule are split into top-level rules for you.
  • @emotion/jest serializers have no styler counterpart. Class names are vl-<hash>.
  • Remove @emotion/* and @vitus-labs/connector-emotion from package.json once nothing imports them.

Find what needs attention

grep -rnE "@emotion/|css=\{|jsxImportSource|styled\.[a-z]+\(|styled\([A-Za-z]+\)\(|withTheme|ClassNames|\bcx\(|<Global|CacheProvider|createCache|extractCritical|styled\.[a-z]+<" src
Edit on GitHub

Last updated on

On this page