Guide
Define a custom element, use it on your page, then move it to another project as JSON or a standalone script. This guide covers each step and the rules that make components portable.
Install
npm install shared-component-builder
import ComponentBuilder from 'shared-component-builder';
const builder = new ComponentBuilder();
Without a bundler, load the UMD build with a script tag. It sets
window.ComponentBuilder.
<script src="https://unpkg.com/shared-component-builder/dist/component-builder.umd.js"></script>
<script>
const builder = new ComponentBuilder();
</script>
CommonJS works too: const ComponentBuilder = require('shared-component-builder');
Your first component
Call define with a tag name and a definition. The element is registered straight
away, so you can use it in your HTML.
builder.define('hello-badge', {
props: ['name'],
template: (props, state, { escape }) => `
<p>Hello, ${escape(props.name)}!</p>
`,
styles: `
p { margin: 0; padding: 6px 12px; border-radius: 999px; background: #e3e5fc; }
`
});
<hello-badge name="Ada"></hello-badge>
Choosing a name
Tag names follow the custom element rules: lowercase, starting with a letter, and containing
at least one hyphen. Letters, digits, ., _ and - are
allowed. my-button and acme.date-picker work;
button, MyButton and 2-col don't.
A browser can't redefine a custom element, so calling define twice with the same
name throws an error. To ship a new version alongside an old one, give it a new name such as
hello-badge-v2.
Templates and props
A template is a function that returns an HTML string:
-
propsholds the current value of every attribute listed inprops. Values are always strings. A missing attribute is''. stateis the element's state object. See State and lifecycle.helpers.escape(value)HTML-escapes a value.
Changing an attribute listed in props re-renders the element. Attributes not in
the list are ignored.
builder.define('price-tag', {
props: ['amount', 'currency'],
template: (props, state, { escape }) => {
const value = Number(props.amount || 0).toFixed(2);
return `<span>${escape(props.currency || '$')}${value}</span>`;
}
});
document.querySelector('price-tag').setAttribute('amount', '12.5'); // re-renders
Props aren't escaped automatically. Anything that could contain user input should go through
escape() before it reaches the HTML. Values you parse yourself, such as
JSON.parse(props.items), need escaping when you output them.
Templates can also be regular functions or method shorthand. All three forms survive export and import:
template: (props) => `...`
template: function (props) { return `...`; }
template(props) { return `...`; }
Content placed inside the element in the page can be shown with a <slot>,
as with any Shadow DOM element.
Styles
styles is a CSS string added to the element's Shadow DOM. Rules only apply inside
the element, and the page's CSS doesn't reach in. Use :host to style the element
itself.
styles: `
:host { display: inline-block; }
:host([hidden]) { display: none; }
button { font: inherit; }
`
Inherited properties such as color and font still flow in from the
page, and CSS custom properties do too. That makes custom properties a good way to let the host
page theme a component:
styles: `button { background: var(--badge-accent, #3340e0); }`
Events and methods
Put on-<event>="methodName" on any element in the template. When that event
happens on the element or anything inside it, the method is called on the component:
builder.define('like-button', {
initialState: { likes: 0 },
template: (props, state) => `
<button on-click="like" data-amount="1">♥ ${state.likes}</button>
`,
methods: {
like(event, element) {
this.setState({ likes: this.state.likes + Number(element.dataset.amount) });
}
}
});
Supported events: click, dblclick, input,
change, submit, keydown, keyup,
focusin, focusout, pointerdown and
pointerup. If several nested elements have a handler for the same event, the
innermost one wins. If the named method doesn't exist, a warning is logged.
For a submit handler, call event.preventDefault() to stop the page
from navigating.
Write methods as method shorthand or regular functions, not arrow functions, so that
this is the element. Methods can take arguments and call each other, and you can
call them from outside: document.querySelector('like-button').like().
Don't use inline handlers such as onclick="this.like()". They run with
this set to the button, not the component.
Telling the page something happened
this.emit(name, detail) dispatches a CustomEvent that bubbles out of
the Shadow DOM, so the page can listen for it on the element, on a parent, or on
document.
methods: {
close() {
this.emit('modal-close', { reason: 'button' });
this.setAttribute('visible', 'false');
}
}
document.addEventListener('modal-close', (event) => console.log(event.detail.reason));
State and lifecycle
initialState sets each element's starting state. Every element gets its own copy,
so two counters on a page never share a count. It has to be JSON-serializable: plain objects,
arrays, strings, numbers, booleans and null.
this.setState(partial) merges the object you pass into the current state and
re-renders. Assigning to this.state directly doesn't re-render; call
this.render() yourself if you do.
mounted() runs each time the element is added to the page, after its first
render. Use setState there if the starting state depends on attributes:
builder.define('tally-counter', {
props: ['start'],
initialState: { count: 0 },
template: (props, state) => `<output>${state.count}</output>`,
mounted() {
this.setState({ count: Number(this.props.start || 0) });
}
});
What happens when an element is added to the page:
- Attribute values listed in
propsare read intothis.props. - The template renders once.
mounted()runs.- From then on, attribute changes and
setStatere-render.
Rendering replaces the Shadow DOM contents, so focus and text typed into inputs inside the element are reset on each render. Keep input values in state if you need them across renders.
Exporting
export returns the component in the format you ask for:
const json = await builder.export('tally-counter'); // { type: 'json', data, usage }
const js = await builder.export('tally-counter', { type: 'script' }); // standalone script (string)
await builder.export('tally-counter', { type: 'cloud' }); // POST to your server
The JSON data holds the name, version, props, styles, initial state and the source text of
the template, methods and mounted. Any extra non-function fields you add to the
definition, such as description or author, are kept too. Save it
wherever suits you: a file in a repository, a CDN, a database.
const { data } = await builder.export('tally-counter');
fs.writeFileSync('tally-counter.json', JSON.stringify(data, null, 2));
Importing
import accepts any of these and returns the registered name:
| Source | Example |
|---|---|
Component data or the export() result | builder.import(json) |
| A JSON string | builder.import('{"name":"tally-counter", …}') |
| A URL | builder.import('https://cdn.example.com/tally-counter.json') |
| A path on the same site | builder.import('/components/tally-counter.json') |
| A name on your component server | builder.import('tally-counter') |
Strings starting with { are parsed as JSON. Strings starting with
http://, https://, //, /,
./ or ../ are fetched. Anything else is loaded by name from your
component server.
To register a component under a different tag name, pass name:
await builder.import(json, { name: 'acme-counter' });
Imports are checked before anything is registered: an invalid name, a missing template, or
source that doesn't evaluate to a function throws an error and leaves the page unchanged.
A response with a non-2xx status rejects with an error that includes the status, for example
Request to /components/x.json failed with status 404 Not Found.
Standalone scripts
A script export is a single file that registers the element without this library. Use it for sites where you can't, or don't want to, install anything.
const js = await builder.export('tally-counter', { type: 'script' });
fs.writeFileSync('public/tally-counter.js', js);
<script src="/tally-counter.js"></script>
<tally-counter start="3"></tally-counter>
The script supports everything a defined component does: props, state, methods,
on-* events, emit and mounted. It also sets a global
named after the component (for example window.TallyCounter). If an element with
the same name is already registered, it logs a warning and does nothing.
Script exports don't use eval or new Function, so they work on pages
with a strict Content Security Policy.
Using a component server
Set apiEndpoint to save and load components by name. A trailing slash is
ignored.
const builder = new ComponentBuilder({ apiEndpoint: 'https://components.example.com/api' });
Your server needs two routes:
| Route | Used by | Request and response |
|---|---|---|
POST /components |
export(name, { type: 'cloud' }) |
JSON body is the component data. Whatever JSON you return is passed back to the caller. |
GET /components/:name |
import(name) |
Return the component data as JSON. The name is URL-encoded. |
A minimal Express server, storing components in memory:
import express from 'express';
const app = express();
const components = new Map();
app.use(express.json({ limit: '1mb' }));
app.post('/api/components', (req, res) => {
components.set(req.body.name, req.body);
res.status(201).json({ saved: req.body.name });
});
app.get('/api/components/:name', (req, res) => {
const component = components.get(req.params.name);
if (!component) return res.status(404).json({ error: 'Not found' });
res.json(component);
});
app.listen(3000);
Anyone who can write to this server can run code in every project that imports from it. Put
authentication in front of POST before using it beyond your own machine.
Writing shareable components
Components travel as source text, and the code is rebuilt in the project that imports it. In the project where you define a component, everything works because the original functions are used. These rules are about what still works after it moves.
Keep functions self-contained
Templates, methods and mounted can only use their arguments, this
and browser globals. Variables, imports and helper functions from the surrounding file are not
exported.
// Breaks after import: formatPrice isn't sent along
import { formatPrice } from './utils.js';
template: (props) => `<span>${formatPrice(props.amount)}</span>`
// Works everywhere: the logic lives inside the template
template: (props) => `<span>$${Number(props.amount).toFixed(2)}</span>`
If several methods need the same helper, make it a method and call it with
this.helper().
Use regular functions for methods
Arrow functions don't get the element as this. Use increment() { … }
or increment: function () { … }.
Keep state JSON-friendly
initialState is copied with JSON, so dates become strings and functions,
Maps and class instances are lost. Store plain data and convert it when you
render.
Test the round trip
Import a component under a new name in the same page to check it works after it moves:
const json = await builder.export('tally-counter');
await new ComponentBuilder().import(json, { name: 'tally-counter-check' });
document.body.insertAdjacentHTML('beforeend', '<tally-counter-check></tally-counter-check>');
Security
-
Importing runs code.
importevaluates the component's template, methods andmounted. Treat a component URL like a script URL: only import from sources you trust. -
Escape user input. Templates produce HTML. Pass anything that could come from
a user through
escape(). -
Content Security Policy.
importusesnew Function, which needs'unsafe-eval'in your CSP.defineand standalone script exports don't.
Node.js and build scripts
Node has no customElements, so define and import only
update the registry there and don't register an element. Everything else works, which makes
Node a good place to generate script exports during a build:
// scripts/export-components.js
const fs = require('fs');
const ComponentBuilder = require('shared-component-builder');
const builder = new ComponentBuilder();
builder.define('tally-counter', require('../src/components/tally-counter'));
builder.export('tally-counter', { type: 'script' }).then((js) => {
fs.writeFileSync('dist/tally-counter.js', js);
});
TypeScript
Types ship with the package. ComponentDefinition types this inside
templates, methods and mounted as a ComponentInstance, so
this.setState and this.emit are checked.
import ComponentBuilder, { type ComponentDefinition } from 'shared-component-builder';
const counter: ComponentDefinition = {
props: ['start'],
initialState: { count: 0 },
template: (props, state) => `<output>${state.count}</output>`,
methods: {
increment() {
this.setState({ count: this.state.count + 1 });
}
}
};
new ComponentBuilder().define('tally-counter', counter);
export() is typed by its type option: 'script'
resolves to a string and the default resolves to a JsonExport.
Troubleshooting
"Component "x-y" is already defined"
That tag name is already registered on the page, by this builder, another builder or a script
export. Custom elements can't be redefined. Pick a new name, or pass
{ name } when importing.
"Invalid component name"
See Choosing a name. The name needs a hyphen and lowercase letters.
"… is not defined" after importing
The template or a method uses a variable from the file it was written in. See Keep functions self-contained.
"no method "save" for on-click"
The template names a method that isn't in methods. Check the spelling in both
places.
Clicking does nothing, or this.setState is not a function
Either the template uses an inline onclick attribute, or the method is an arrow
function. Use on-click="method" and method shorthand.
The page doesn't hear an event from the component
Use this.emit(name). A CustomEvent created by hand doesn't bubble
out of the element unless you set bubbles and composed.