What is @emotion/server?
@emotion/server is a library that provides server-side rendering (SSR) utilities for Emotion, a popular CSS-in-JS library. It allows you to extract and inline critical CSS for your React components during server-side rendering, ensuring that styles are available immediately when the page loads.
What are @emotion/server's main functionalities?
renderStylesToString
This function takes the HTML string generated by React's renderToString and adds the necessary style tags to it. This ensures that the critical CSS is inlined in the HTML, improving the initial load performance.
const { renderStylesToString } = require('@emotion/server');
const React = require('react');
const { renderToString } = require('react-dom/server');
const App = require('./App');
const html = renderStylesToString(renderToString(<App />));
console.log(html);
renderStylesToNodeStream
This function works similarly to renderStylesToString but is designed for streaming. It takes a Node.js stream of HTML and adds the necessary style tags to it, allowing for more efficient server-side rendering in streaming scenarios.
const { renderStylesToNodeStream } = require('@emotion/server');
const React = require('react');
const { renderToNodeStream } = require('react-dom/server');
const App = require('./App');
const { PassThrough } = require('stream');
const stream = renderToNodeStream(<App />).pipe(renderStylesToNodeStream());
stream.pipe(process.stdout);
Other packages similar to @emotion/server
styled-components
styled-components is another popular CSS-in-JS library that supports server-side rendering. It provides a similar feature set, including the ability to extract and inline critical CSS during SSR. However, styled-components uses a different API and styling approach compared to Emotion.
aphrodite
Aphrodite is a CSS-in-JS library that also supports server-side rendering. It allows you to generate critical CSS and inline it during SSR. Aphrodite is less feature-rich compared to Emotion and styled-components but is known for its simplicity and performance.
linaria
Linaria is a zero-runtime CSS-in-JS library that supports server-side rendering. It extracts CSS at build time, which can then be inlined during SSR. Linaria offers a different approach by avoiding runtime overhead, making it a good choice for performance-critical applications.
@emotion/server
Extract and inline critical css with emotion.
@emotion/server
provides three APIs for doing server-side rendering with emotion to extract critical css, inline critical css in html to a string and inline critical css in html to a stream.
@emotion/server
's APIs are documented here.
npm install --save @emotion/css @emotion/server