wc-ssr
TypeScript icon, indicating that this package has built-in type declarations

0.0.14 • Public • Published

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" }));

Package Sidebar

Install

npm i wc-ssr

Weekly Downloads

1

Version

0.0.14

License

MIT

Unpacked Size

36.7 kB

Total Files

24

Last publish

Collaborators

  • keiya01