css
css copied to clipboard
✨ Master CSS React Stream
Description
- #159
This Stream API is currently only used as a pipeline for SSR. We recommend you asynchronously load the JIT engine for CSS hydration after the page is initialized.
class CSSStream extends Transform {
constructor(config?: Config) {
let inserted = false
let content = ''
super({
transform(chunk: Buffer, _, callback) {
content += chunk.toString()
if (inserted ? content.endsWith('</script>') : content.endsWith('</body></html>')) {
this._flush(callback)
} else {
callback()
}
},
flush(callback) {
if (content) {
if (!inserted) {
inserted = true
content = renderIntoHTML(content, config)
}
this.push(content)
content = ''
}
callback()
},
})
}
}
For Remix:
// app/entry.server.tsx
import { CSSStream } from '@master/css.react'
function handleBrowserRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext
) {
return new Promise((resolve, reject) => {
let didError = false
const { pipe, abort } = renderToPipeableStream(
<RemixServer context={remixContext} url={request.url} />,
{
onShellReady() {
const body = new CSSStream(config) // SSR
responseHeaders.set('Content-Type', 'text/html')
resolve(
new Response(body, {
headers: responseHeaders,
status: didError ? 500 : responseStatusCode,
})
)
pipe(body)
},
...
}
)
...
})
}