npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

wc-ssr

v0.0.14

Published

SSR with web components

Downloads

8

Readme

wc-ssr

NOTE: This library is EXPERIMENTAL.

wc-ssr is a simple Server Side Rendering Library with Web Components.
This lib is worked by Declarative Shadow DOM. Therefore this lib works to use Server Side Rendering on a supported browser but works to use Client Side Rendering on a not supported browser.

SSR with Web Components

This lib work as SSR in the browser that support Declarative Shadow DOM. But this lib perform as Client Side Rendering in not supported browsers.

Installation

npm install wc-ssr

or

yarn add wc-ssr

Example

// client/AddButton/template.ts

import { html, $props, $event, $shadowroot } from "wc-ssr";

type Props = {
  title: string;
  onClick?: () => void;
};

export const template = (props: Props) => html`
  ${/* You can pass props with `$props()`. */}
  <add-button ${$props(props)}>
    ${/* You must set shadowroot attribute to use ShadowDOM */}
    <template ${$shadowroot('open')}>
      ${/* You can add event with `$event()`. */}
      <button type="button" ${$event("click", props.onClick)}>
        ${props.title}
      </button>
    </template>
  </add-button>
`;
// client/AddButton/element.ts

import { BaseElement } from "wc-ssr/client";
import { template } from "./template";

export class AddButton extends BaseElement {
  constructor() {
    super();
  }

  render() {
    // `props` is injected to `this.props`.
    return template({
      title: this.props.title,
      onClick: this.props.onClick,
    });
  }
}

customElements.define("add-button", AddButton);

NOTE: When you use SSR feature, you can not load BaseElement on the server. You must avoid loading BaseElement like this example. This is because, BaseElement inherit HTMLElement.

// client/AddButton/index.ts

export { template } from "./template";
if (IS_CLIENT) {
  import(/* webpackMode: "eager" */ "./element");
}
// page.ts

import { html } from 'wc-ssr';
import { template as AddButton } from './client/AddButton';

export const renderPage = () => html`
  <div>
    <h1>Hello World!</h1>
    ${AddButton({ title: 'button', onClick: () => console.log('clicked!') })}
  </div>
  `;
}
// server.ts

import fastify, { FastifyInstance } from "fastify";
import { Server, IncomingMessage, ServerResponse } from "http";
import { htmlToString } from "wc-ssr";
import { renderPage } from './page';

type App = FastifyInstance<
  Server,
  IncomingMessage,
  ServerResponse,
>;

const start = async () => {
  const app = fastify();

  app.get("/example", async (req, reply) => {
    reply.header("Content-Type", "text/html; charset=utf-8");
    reply.send(`
      <DOCTYPE!>
      <html>
        <body>
          ${htmlToString(renderPage())}
        </body>
      </html>
    `);
    );
  });

  try {
    await app.listen(3000);
  } catch (err) {
    app.log.error(err);
    process.exit(1);
  }
};

start();

See detail in example.

Usage

ShadowDOM

You must use $shadowroot method to tell custom element use ShadowDOM.

$shadowroot method can take open or closed.
This is optional. Default value is open.

import { html, $shadowroot } from "wc-ssr";

export const template = html`
  <custom-element>
    <template ${$shadowroot("open")}>
      <span>Hello World</span>
    </template>
  </custom-element>
`;

Styling

You can use css with style tag.
You can set style tag inside template tag.

import { html, $shadowroot } from "wc-ssr";

const style = html`
  <style>
    button {
      color: red;
    }
  </style>
`;

const CustomButton = html`
  <custom-button>
    <template ${$shadowroot()}>
      ${style}
      <button type="button">button</button>
    </template>
  </custom-button>
`;

You can also set multiple styles as the following.

const style = html`
  <link rel="stylesheet" href="example1.css" />
  <link rel="stylesheet" href="example2.css" />
  <style>
    div {
      background-color: blue;
    }
  </style>
`;

Props

You can pass props to component. And you can get props to be injected from BaseElement class.

import { html, $shadowroot } from "wc-ssr";
import { BaseElement } from "wc-ssr/client";

const CustomElement = html`
  <custom-element>
    <template ${$shadowroot()}>
      <h1>Hello World</h1>
      ${
        PassProps({
          text: "This is paragraph",
        }) /* Pass props to PassProps component */
      }
    </template>
  </custom-element>
`;

class CustomElement extends BaseElement {
  /* ... */
}

const PassProps = ({ text }) => html`
  <pass-props ${$props({ text }) /* Pass props to pass-props element */}>
    <template ${$shadowroot()}>
      <p>${text}</p>
    </template>
  </pass-props>
`;

class PassProps extends BaseElement {
  constructor() {
    super();
  }

  render() {
    return PassProps({ ...this.props });
  }
}

Event

You can add event to element by using $event method.

import { html, $shadowroot, $event } from "wc-ssr";
import { BaseElement } from "wc-ssr/client";

const EventElement = ({ handleOnClick }) => html`
  <event-element>
    <template ${$shadowroot()}>
      <button type="button" ${$event("click", handleOnClick)}>click me</button>
    </template>
  </event-element>
`;

class EventElementClass extends BaseElement {
  constructor() {
    super();
  }

  handleOnClick = () => {
    console.log("Clicked!!");
  };

  render() {
    return EventElement({ handleOnClick: this.handleOnClick });
  }
}

State

You can define state like React. If you defined state and change it, render() is executed.

import { html, $shadowroot, $event } from "wc-ssr";
import { BaseElement } from "wc-ssr/client";

type Props = {
  items: string[];
  text: string;
  handleOnChangeText: (e?: InputEvent) => void;
  addItem: () => void;
};

const DefineState = ({ items, text, handleOnChangeText, addItem }) => html`
  <define-state>
    <template ${$shadowroot()}>
      <ul>
        ${items.map((item) => html`<li>${item}</li>`)}
      </ul>
      <input
        type="text"
        value="${text || ""}"
        ${$event("input", handleOnChangeText)}
      />
      <button type="button" ${$event("click", addItem)}>add item</button>
    </template>
  </define-state>
`;

class DefineState extends BaseElement {
  constructor() {
    super();
    this.state = {
      items: [],
      text: [],
    };
  }

  addItem = () => {
    this.setState({ items: [...this.state.items, this.state.text] });
  };

  handleOnChangeText = (e?: InputEvent) => {
    const target = e?.target as HTMLInputElement;
    if (target) {
      this.setState({ text: target.value });
    }
  };

  render() {
    return DefineState({
      items: this.state.items,
      text: this.state.text,
      handleOnChangeText: this.handleOnChangeText,
      addItem: this.addItem,
    });
  }
}

Attribute

TODO

Lifecycle

You can use web components lifecycle like below.

connectedCallback() {
  super.connectedCallback();
  console.log('connected!!');
}

And you can use additional lifecycle.

  • componentDidMount ... This function is invoked when all preparation of BaseElement is completed.
componentDidMount() {
  super.componentDidMount();
  this.setState({ text: this.props.text });
}

Hydration

Hydration is performed automatically by browser.

Server Side Rendering

You can use htmlToString to render html on the server.

import { htmlToString, html, $shadowroot } from "wc-ssr";

type Props = {
  text: string;
};

const render = ({ text }: Props) => html`
  <custom-element>
    <template ${$shadowroot()}>
      <h1>${text}</h1>
    </template>
  </custom-element>
`;

htmlToString(render({ text: "Hello World" }));