Introduction
Web Components Compiler (WCC) is a NodeJS package designed to make server-side rendering (SSR) of native Web Components easier. It can render (within reason 😅) your Web Component into static HTML. This includes support for Declarative Shadow DOM.
Installation
WCC can be installed from npm.
$ npm install wc-compiler --save-dev
Key Features
- Supports the following
HTMLElement
lifecycles and methods on the server sideconstructor
connectedCallback
attachShadow
innerHTML
[get|set|has]Attribute
<template>
/DocumentFragment
addEventListener
(as a no-op)- Supports
CSSStyleSheet
(all methods act as no-ops) - TypeScript
- Custom JSX parsing
- Recursive rendering of nested custom elements
- Metadata and runtime hints to support various progressive hydration and lazy loading strategies
It is recommended to reference
globalThis
instead ofwindow
for isomorphic Web Components.
Usage
WCC exposes a few utilities to render your Web Components. See our API docs for all available features.
-
Given a custom element like so:
const template = document.createElement('template'); template.innerHTML = ` <style> .footer { color: white; background-color: #192a27; } </style> <footer class="footer"> <h4>My Blog © ${new Date().getFullYear()}</h4> </footer> `; class Footer extends HTMLElement { connectedCallback() { if (!this.shadowRoot) { this.attachShadow({ mode: 'open' }); this.shadowRoot.appendChild(template.content.cloneNode(true)); } } } export default Footer; customElements.define('wcc-footer', Footer);
-
Using NodeJS, create a file that imports
renderToString
and provide it the path to your web componentimport { renderToString } from 'wc-compiler'; const { html } = await renderToString(new URL('./path/to/footer.js', import.meta.url));
-
You will get the following HTML output that can be used in conjunction with your preferred site framework or templating solution.
<wcc-footer> <template shadowrootmode="open"> <style> .footer { color: white; background-color: #192a27; } </style> <footer class="footer"> <h4>My Blog © 2022</h4> </footer> </template> </wcc-footer>
Make sure to test in Chrome, or other Declarative Shadow DOM compatible browser, otherwise you will need to include the polyfill.