styled-jsx
Documentation about using Vike with styled-jsx
.
💚This page is maintained by the community and may contain outdated information; PR welcome to update or improve it.
If you are using vike-react you can use vike-react-styled-jsx
for automatic integration.
The
vike-react-styled-jsx
extension requiresvike-react
.
Manual integration
If you use vike-react
, you can manually integrate styled-jsx
by using:
Example:
Without vike-react
To use Vike with styled-jsx
without vike-react
:
-
Install:
npm install styled-jsx
-
Add
styled-jsx
tovite.config.js
:// vite.config.js import react from '@vitejs/plugin-react' import vike from 'vike/plugin' export default { plugins: [react({ babel: { plugins: ['styled-jsx/babel'] } }), vike()] }
-
Collect and inject styles.
When using a CSS-in-JS tool, like
styled-jsx
, you always need to collect the page's styles upon SSR in order to avoid FOUC.// /renderer/+onRenderHtml.js export { onRenderHtml } import React from 'react' import { renderToString, renderToStaticMarkup } from 'react-dom/server' import { escapeInject, dangerouslySkipEscape } from 'vike/server' import { Layout } from './Layout' import { createStyleRegistry, StyleRegistry } from 'styled-jsx' const registry = createStyleRegistry() async function onRenderHtml(pageContext) { // flush styles to support the possibility of concurrent rendering registry.flush() const { Page } = pageContext // include the styleregistry in the app render to inject the styles const viewHtml = dangerouslySkipEscape( renderToString( <StyleRegistry registry={registry}> <Layout> <Page /> </Layout> </StyleRegistry> ) ) // extract the styles to add as head tags to the server markup const headTags = renderToStaticMarkup(<>{registry.styles()}</>) return escapeInject`<!DOCTYPE html> <html> <head> ${dangerouslySkipEscape(headTags)} </head> <body> <div id="root">${viewHtml}</div> </body> </html>` }
Example:
-
2023.07 GitHub >
jeremypress/vite-ssr-styled-jsx
vite-plugin-ssr was the previous name of Vike.