Web Component Generator
Configure a custom element and get a complete, runnable class with correct reflection semantics in JS or TypeScript.
Component configuration
2 attribute(s) · 0 event(s)Generated source
user-card · JS/**
* UserCard — generated by Web Component Generator.
* Registers <user-card> as an autonomous custom element.
*/
const TEMPLATE = `<div part="root"><span data-attr="name"></span><slot></slot></div>`;
const STYLES = `:host { display: block; }`;
class UserCard extends HTMLElement {
/** Captured at attachShadow time so closed roots stay usable. */
#root;
static get observedAttributes() {
return ["name", "count"];
}
constructor() {
super();
this.#root = this.attachShadow({ mode: "open" });
const style = document.createElement("style");
style.textContent = STYLES;
this.#root.append(style);
// Pre-upgrade assignment: mirror own properties into accessors.
for (const name of ["name", "count"]) {
if (Object.prototype.hasOwnProperty.call(this, name)) {
const value = this[name];
delete this[name];
this[name] = value;
}
}
}
attributeChangedCallback(name, _oldValue, value) {
switch (name) {
case "name":
this.#setName(value ?? "Guest");
break;
case "count":
this.#setCount(value === null || value.trim() === "" || Number.isNaN(Number(value)) ? 0 : Number(value));
break;
default:
break;
}
}
#setName(value) {
if (this["name"] === value) return;
this["name"] = value;
this.setAttribute("name", String(value));
this.#scheduleRender();
}
get "name"() {
return this.getAttribute("name") ?? "Guest";
}
set "name"(value) {
this.#setName(value);
}
#setCount(value) {
if (this["count"] === value) return;
this["count"] = value;
this.#scheduleRender();
}
get "count"() {
const raw = this.getAttribute("count");
return raw === null || raw.trim() === "" || Number.isNaN(Number(raw)) ? 0 : Number(raw);
}
set "count"(value) {
this.#setCount(value);
}
#renderScheduled = false;
#scheduleRender() {
if (this.#renderScheduled) return;
this.#renderScheduled = true;
queueMicrotask(() => {
this.#renderScheduled = false;
this.#render();
});
}
#render() {
this.#root.innerHTML = TEMPLATE;
const nameField = this.#root.querySelector('[data-attr="name"]');
if (nameField) nameField.textContent = String(this["name"]);
const countField = this.#root.querySelector('[data-attr="count"]');
if (countField) countField.textContent = String(this["count"]);
}
connectedCallback() {
this.#scheduleRender();
}
}
// SSR guard: customElements only exists in a browser document.
if (typeof customElements !== "undefined" && !customElements.get("user-card")) {
customElements.define("user-card", UserCard);
}Details
Fill in a form and receive a complete, runnable custom-element class: a define guard, observedAttributes, per-type attribute coercion and reflection, private accessors with pre-upgrade clobbering protection, a shadow template with named slots, constructable stylesheets with a fallback, lifecycle callbacks, a CustomEvent helper and typed TypeScript output with an HTMLElementTagNameMap entry. The generated JS is compile-checked before display, and a usage snippet shows the import and markup. Everything is generated locally; no code is executed by the tool.
More examples
User card
tag: user-card · attributes: name (string, reflected), count (number) · slot: defaultThe default preset emits a class with attributeChangedCallback, getters/setters and a shadow template that renders the current name.
Event button
tag: action-button · event: select { bubbles: true, composed: true }A component that dispatches a composed CustomEvent with typed detail through an emitSelect helper.
Typed form field
tag: form-field · language: TypeScript · formAssociated: trueTyped properties, ElementInternals scaffolding and form lifecycle callbacks in one emitted file.
Examples
User card
tag: user-card; attribute: name (string, reflect)class UserCard with observedAttributes and a reflected name accessorThe customElements.define guard avoids duplicate registration errors when the script loads twice.
Number safety
attribute: count (number, default 5); setAttribute("count", "abc")count === 5Empty strings and NaN fall back to the default instead of silently injecting invalid numbers.
Closed shadow
shadow: closedthis.#root = this.attachShadow({ mode: "closed" })A captured private root keeps #render working even though element.shadowRoot stays null.
About this tool
Web Component Generator turns a form of choices into a complete custom element class. Set the tag name, add attributes with types and reflection, pick an open or closed shadow root, write CSS and a template, declare slots, lifecycle callbacks and events, and the tool emits runnable JavaScript or TypeScript plus a usage snippet.
The emitter deliberately handles the ceremony that is easy to get wrong: a customElements.define guard, observedAttributes, attributeChangedCallback with safe coercion, private property accessors that re-render on change, and a pre-upgrade assignment guard for properties set before the element upgrades. Closed shadow roots keep a captured root reference, so rendering does not depend on the public shadowRoot being readable.
Number attributes fall back to their default for empty or non-numeric values instead of injecting NaN; boolean attributes use presence semantics; enum attributes validate against a list. Constructable stylesheets are emitted with an automatic inline-style fallback for browsers that lack them. Custom events are created with the bubbles, composed and cancelable flags you choose.
The JS output is syntax-checked with a compile-only parse before it is shown, invalid tag names are blocked with the exact spec rule, and nothing is executed or uploaded. Four presets — user card, event button, constructable styles and a typed form field — provide a starting point.
What this tool does not do
- Only autonomous custom elements are emitted; customized built-in elements (extends) are not supported.
- The TypeScript output is not compile-checked in the browser; the JS variant is checked with a compile-only parse.
- Rendering uses a full innerHTML swap of the shadow root, which is simple but resets focus and local state.
- The browser preview is not executed by the tool; run the emitted code in your own project to verify behaviour.
- Config drafts are not persisted between visits.
How to use this tool
Name the element
Enter a lowercase, hyphenated tag name such as user-card. The validator explains spec rules immediately and blocks output until the name is legal.
Add attributes
Give each attribute a name, type (string, number, boolean or enum), default value and reflection toggle. Enum attributes also take a pipe-separated list of allowed values.
Configure shadow DOM
Choose open or closed mode, optionally enable constructable stylesheets, and edit the CSS and HTML template. Named slots are added in their own section.
Choose lifecycle and events
Toggle connected/disconnected/adopted callbacks, lazy rendering or form association, then declare the events the component should dispatch.
Copy or download
Switch between JS, TypeScript and Usage tabs, copy the source, or download it as a .ts/.js file. The JS variant is syntax-checked before display.
Use cases
Design systems without a framework
Scaffold native components with consistent attribute reflection and shadow styling across a team.
Embed widgets
Emit a single self-contained class plus a script-tag usage snippet for third-party pages.
Teaching the platform
Show students a correct, complete custom element rather than disconnected fragments.
TypeScript design systems
Generate typed accessors and an HTMLElementTagNameMap entry for editor autocomplete.
Attribute coercion at a glance
| Type | Attribute → property |
|---|---|
| string | getAttribute(name) with the configured default when absent |
| number | Number(value) with a default for empty strings, null and NaN |
| boolean | hasAttribute(name); setting reflects to presence, not a string value |
| enum | Only values in the allowed list are accepted; anything else falls back to the default |
Reflected properties call setAttribute (or removeAttribute for false booleans) and schedule a microtask re-render.
Common mistakes
Mistake:Using a tag name without a hyphen.
Fix:The custom element spec requires a hyphen; the validator blocks the name and explains the rule.
Mistake:Reading this.shadowRoot in a closed-root component.
Fix:The emitted class captures the root in a private #root field at attachShadow time.
Mistake:Treating a boolean attribute's text as its value.
Fix:Boolean attributes use presence: hasAttribute for reads, setAttribute/removeAttribute for writes.
Mistake:Assuming a property assigned before upgrade reaches the accessor.
Fix:The constructor emits an own-property upgrade guard that deletes and reassigns pre-upgrade values.
Mistake:Expecting composed events to be blocked by a closed shadow root.
Fix:Composed CustomEvents still cross closed roots; only direct shadowRoot access is blocked.
Frequently asked questions
What are custom element name rules?
A custom element tag must contain a hyphen, start with a lowercase letter, contain only lowercase letters, digits, dots, underscores and hyphens (plus certain Unicode name characters), and must not be one of the eight names reserved by the HTML specification, such as font-face or missing-glyph. The generator checks all of these as you type and shows the exact failing rule.
Should I use an open or closed shadow root?
Open roots expose element.shadowRoot to outside code, which is convenient for testing and styling; closed roots hide it. The emitted class captures the root in a private field at attachShadow time, so rendering works in both modes. Events marked composed still escape a closed root — only direct access is blocked.
How do attributes and properties stay in sync?
Attributes are observed through attributeChangedCallback and coerced by type: numbers use Number(value) with a safe default, booleans use presence, strings use getAttribute with a default, and enums validate against your allowed list. When reflection is enabled, setting a property calls setAttribute (or removeAttribute for false booleans); changing the attribute updates the property back through the callback.
Does it support slots and styles?
Yes. Add default or named slots with optional fallback content and they are included in the shadow template. You can write component CSS directly, choose inline <style> or constructable stylesheets, and the constructable path emits a try/catch fallback that appends a style element when CSSStyleSheet is unavailable.
Can I use the generated component in React or Vue?
Yes — custom elements work in most frameworks. In React 19+ they can be used directly in JSX; in older versions you typically set attributes via refs. Strings and numbers pass as attributes; complex data should be assigned as properties after the element upgrades. The Usage tab shows a plain HTML import and markup example.
Does the tool run or upload my generated code?
No. The emitter only produces text. The JavaScript variant is syntax-checked with a compile-only Function parse — it is never executed — and nothing is sent to a server. Run or paste the generated source in your own project when you are ready.
References & standards
Related tools
.env Secret Safety Linter
Validate .env syntax and spot likely leaked credentials or placeholder secrets.
.gitattributes Generator
Build .gitattributes rules for line endings, Git LFS, GitHub linguist marks and merge drivers — with a one-line explanation for every rule.
.htaccess Generator
Build an Apache .htaccess — HTTPS redirects, rewrites, error pages, security headers, and basic auth
2D Fluid Dynamics & Particle Physics Sandbox
A physics playground with two engines sharing one canvas. The fluid mode runs a real Eulerian Navier-Stokes solver — semi-Lagrangian advection, explicit diffusion, Jacobi pressure projection and vorticity confinement — that you paint with dye and velocity using mouse or touch. The particle mode is a damped Verlet N-body engine with gravity wells, Coulomb attractors and repulsors, spring links, wall restitution and elastic circle collisions. Particle counts adapt to the device (100k target on WebGL2 desktop, 2k-5k on CPU fallback), and every configuration exports as runnable code: a Matter.js world, a PixiJS ticker setup, or a standalone vanilla Canvas engine.
A/B Test Sample Size Calculator
Compute required sample size per variant and test duration from baseline conversion rate, minimum detectable effect, alpha and power.
ABA Routing Number Validator
Validate 9-digit US ABA routing numbers with 3-7-1 Mod-10 breakdown.