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

  1. Supports the following HTMLElement lifecycles and methods on the server side
    • constructor
    • connectedCallback
    • attachShadow
    • innerHTML
    • [get|set|has]Attribute
  2. <template> / DocumentFragment
  3. addEventListener (as a no-op)
  4. Supports CSSStyleSheet (all methods act as no-ops)
  5. Recursive rendering of nested custom elements
  6. Metadata and runtime hints to support various progressive hydration and lazy loading strategies

It is recommended to reference globalThis instead of window for isomorphic Web Components.

Usage

WCC exposes a few utilities to render your Web Components. See our API docs for all available features.

  1. 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 &copy; ${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);
    
  2. Using NodeJS, create a file that imports renderToString and provide it the path to your web component

    import { renderToString } from 'wc-compiler';
    
    const { html } = await renderToString(new URL('./path/to/footer.js', import.meta.url));
    
  3. 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 &copy; 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.