@asphalt-react/ssr
v2.0.0-rc.4
Published
server side rendering for asphalt-react components
Downloads
31
Readme
⚠️ Styles for Asphalt React components are absent on the client on initial request and are loaded when script executes which may cause FOUC or
Flash Of Unstyled Content
for some users. This package is designed to add styles for components and solve FOUC.
Asphalt React SSR
Provides a wrapper React component called SSR
and a function called extractCSS
to add styles when server rendering asphalt-react components.
<SSR> (default)
: Wrap yourApp
withSSR
component for server side rendering to work.
Only wrapped subtree is considered for styling
Following is a pseudocode of a hypothetical client implementation
app.js
import { Button } from "@asphalt-react/button"
import { SSR } from "@asphalt-react/ssr"
const App = () => (
<SSR>
<Button>Click Me</Button>
</SSR>
)
export default App
extractCSS()
: WrapSSR
withextractCSS
function on server side implementation. FunctionextractCSS
returns the following:
const { html,css,id } = extractCSS(...)
html
: html of all wrapped componentscss
: combined css as string of asphalt-react componentsid
: string to uniquely identify style node.
Inject the css
to the html
on the server and apply the id
to the style node.
When the script runs on the browser,
<style>
tag with aboveid
is removed from the document.
Following is a pseudocode of a hypothetical server implementation
server.js
const ReactDOMServer = require("react-dom/server")
const React = require("react")
const App = require("./app.js").default
const { extractCSS } = require("@asphalt-react/asphalt-ssr")
const { html,css,id } = extractCSS(ReactDOMServer.renderToString(React.createElement(App)))
const serverHtml = `<!DOCTYPE html>
<html lang="en">
<head>
<title>My page</title>
<style id=`${id}`>${css}</style>
<meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width" />
</head>
<body>
<div id="root">${html}</div>
</body>
</html>
`
Certain changes may be required to the above code according to implementation.
Installation
# yarn
$ yarn add @asphalt-react/ssr
# npm
$ npm install @asphalt-react/ssr
Local Development
How it works ?
Uses StyleContext
from @asphalt-react/context
for communication between server side and client side. Components receive a function as context's value and pass the respective stylesheet to the function in server environment. A dock
then collects, de-duplicates and ships the styles. extractCSS
returns final styles which are injected to server html.
How to build?
This package is built using @asphalt-react/build
using a custom rollup.config.js.
# yarn
$ yarn rollup -c
# npx
$ npx rollup -c