mi-element
v0.9.0
Published
Build lightweight reactive micro web-components
Readme
mi-element
a lightweight alternative to write web components
Only weights 2.5kB minified and gzipped.
mi-element provides features to build web applications through Web Components like:
- type coercion with setAttribute
- controllers to hook into the components lifecycle
- ContextProvider, ContextConsumer for data provisioning from outside of a component
- Store for managing shared state across components
- Signal for reactive behavior
- optional html literal templating with mi-html using reactive updates
The motivation to build this module comes from the confusions around attributes
and properties. "mi-element" solves this by providing the same results when
setting objects or functions either through el.setAttribute(name, value) or
properties el[name] = value.
Furthermore all observed attributes have a reactive behavior through the use of signals and effects (loosely) following the TC39 JavaScript Signals standard proposal.
Usage
In your project:
npm i mi-element/** @file ./mi-counter.js */
import { MiElement, define, Signal } from 'mi-element'
const { effect, createSignal } = Signal
// define your Component
class MiCounter extends MiElement {
static template = `
<style>
:host { font-size: 1.25rem; }
</style>
<div aria-label="Counter value">0</div>
<button aria-label="Increment counter"> + </button>
`
static get properties() {
// declare reactive attribute(s)
return { count: { type: Number, initial: 0 } }
}
static createSignal = createSignal
// called by connectedCallback()
render() {
// gather refs from template (here by id)
this.refs = this.refsBySelector({ increment: 'button', div: 'div' })
// apply event listeners
this.refs.increment.addEventListener('click', () => {
// change observed and reactive attribute...
this.count++
})
effect(() => {
// ...triggers update on every change of `this.count`
this.refs.div.textContent = this.count
})
}
}
// create the custom element
define('mi-counter', MiCounter)Now use your now component in your HTML
<body>
<mi-counter></mi-counter>
<mi-counter count="-3"></mi-counter>
<script type="module" src="./mi-counter.js"></script>
</body>In ./example you'll find a working sample of a Todo App. Check it out with
npm run example
Documentation
- element mi-element's lifecycle
- render mi-elements html template literal and render function
- controller adding controllers to mi-element to hook into the lifecycle
- signal Signals and effect for reactive behavior
- store Manage shared state in an application
- context Implementation of the Context Protocol.
- styling Styling directives for "class" and "style"
- reactivity Reactivity and templating with mi-html
License
MIT licensed
