popeindustries / lit-html-server

Render lit-html templates on the server as Node.js streams
MIT License
265 stars 12 forks source link

Recommended SW bundling setup #126

Closed jeffposnick closed 4 years ago

jeffposnick commented 4 years ago

Thanks for putting this library together!

I'm trying out lit-html-server in a project that previously performed universal HTML rendering (server side rendering + service worker) via really basic string literals.

The WIP code is at https://github.com/GoogleChromeLabs/so-pwa/tree/lit-html-server

I'm trying to figure out the best way to address the

NOTE: a bundler is required to package modules for use in a Service Worker

mentioned in the docs. I'm already using Rollup, and I have a working config at https://github.com/GoogleChromeLabs/so-pwa/blob/fdced5174172293966d781f37f999fe8b8eed761/rollup.config.js#L77-L95

This ends up pulling in around ~50kb of polyfills needed to get either lit-html-server's renderToStream() or renderToString() methods functional in the service worker. I think most of that is for the stream and buffer polyfills.

I'm curious whether there are any tweaks I can make to that configuration, or some other entry point to the library that I could use, that would minimize the overhead of what's getting pulled in to the service worker bundle. Do you have a bundler config that you recommend?

popeindustries commented 4 years ago

Hi Jeff, thanks for trying this out! The library has been in heavy production use for over a year, including browser rendering of cms preview (body.innerHTML = renderToString(...)), but running in a service worker is still a bit of an experiment.

That said, it should work without any special polyfills. Unless you need to patch Node builtins for something else, you should be able to drop rollup-plugin-node-builtins. The browser bundle ships with a lightweight "fake" Buffer class that just wraps strings, and the streaming is done with the browser's ReadableStream. You can import the browser version directly: @popeindustries/lig-html-server/browser.mjs, or add browser: true to @rollup/plugin-node-resolve config. There are no external dependencies, and the 2 unminified/unzipped source files together are ~40KB.

I'd be happy to fix/change things if you are still having problems getting it to work properly. Let me know.

jeffposnick commented 4 years ago

Ugh, thanks! Everything works as expected now, with templates shared between the server and SW.

I missed the bit about using @popeindustries/lit-html-server/browser.mjs from inside the service worker, and I was pulling in @popeindustries/lit-html-server instead.

Switching to browser: true in the @rollup/plugin-node-resolve configuration also accomplished the same thing, as you say.

jeffposnick commented 4 years ago

(This is now live at https://so-pwa.firebaseapp.com/)