Minimalist rendering library, optimized for web components.
npm install @osmoscraft/web-rendering-libraryMinimalist rendering library, optimized for web components.
- Server side rendering with elements
- Client side hydration with javascript
- Efficiently update DOM between multiple renderings
- Composes with browser APIs, instead of wrapping them
Note: This library only exports TypeScript. So you will need a modern compiler to use it. Currently only supporting vite and esbuild.
``sh`
npm i @osmoscraft/web-rendering-library
Define component in TypeScript
`TypeScript
import { html, useComponent } from "@osmoscraft/web-rendering-library";
// This creates a real HTMLTemplateElement
const template = html
class MyCounter extends HTMLElement {
private component = useComponent(template, this);
connectedCallback() {
this.component.render({
count: 0,
handleClick: () => {
this.component.render(data => ({
count: data.count + 1,
})),
}
});
}
}
customElements.define("my-counter", MyCounter);
`
Use component in HTML
`html`
`TypeScript
// Shadow DOM
useComponent(host, template);
useComponent(host, template, { mode: "open" }); // equivalent to above
// Light DOM
useComponent(host, template, { mode: "none" });
// Update by data patching
component = useComponent(...args);
component.render({ ...newPartialDataObject });
// Update by function
component = useComponent(...args);
component.render((oldData) => ({ ...newPartialDataObject }));
// Typed data
interface Model {
myVar: string;
}
component = useComponent
component.render({ myVar: "helloworld" }); // OK
component.render({ myVar: 123 }); // Type error
// Manual render
render(template, host, fullDataObject);
`
To achieve high performance, this library treats all components as pure. If a components input doesn't change, re-render will have no effect on it.
For each binding, change is determined via strict equal (===).
To build reactive web component with this library, you need to re-render whenever an update should affect the UI. For example:
- Initially in connectedCallback(), call component.render();@click
- On user input
- e.g. handler function should usually call component.render() in the end.attributeChangedCallback()
- In , call component.render();
Simple variable
`html`
`TypeScript`
render(template, container, { myVar: "hello" });
Chained path
`html`
`TypeScript`
render(template, container, { myVar: { mySubVar: "hello" } });
Negation
`html`
`TypeScript`
render(template, container, { myBooleanVar: true });
`html 32">
Note: providing a key can help the diffing algorithm re-use elements when there is no change.
$3
`html
`$3
`html
`Note: Setting
myVar to undefined removes the attribute.$3
`html
`$3
`html
`$3
- Unary operators
-
!
- !!
- Binary operators
- ==
- !==
- !=
- &&
- ||
- >=
- >
- <=
- <
- Primitives
- String, e.g. "hello", or 'hello'
- Number (only integers), e.g. 123, -52, or +999.
- null
- undefined`