Write JavaScript with HTML. Yes, on purpose.
HTMS (Hyper Text Media Script) compiles HTML-flavoured source into reactive web components. The syntax borrows the good bit from ColdFusion: state, loops and events are tags too. The output is regular JavaScript built on Custom Elements, Shadow DOM and DOM events.
<component name="click-counter">
<var name="count" value="0" mutable="true"></var>
<button on:click="count++">Clicked {count} times</button>
</component>The same handler can be written as tags, which is handy when it grows:
<button id="increment">Clicked {count} times</button>
<event target="#increment" type="click">
<set name="count" op="++"></set>
</event>No eval, no Function constructor and no private browser runtime to learn.
HTMS compiles templates ahead of time into code that updates exactly the DOM nodes whose values changed, with no virtual DOM. The only runtime is a set of small helpers emitted into the compiled output. The bench/ suite runs the js-framework-benchmark operations against that project's official Svelte 5, Solid, Vue, React and vanilla JS implementations, all built by the same Vite production build and measured in Chromium from click to paint:
| HTMS | Svelte 5 | Solid | Vue | React | Vanilla JS | |
|---|---|---|---|---|---|---|
| overall time vs vanilla JS | 1.04× | 1.13× | 1.08× | 1.23× | 1.63× | 1.00× |
| bundle size (min + gzip) | 4.6 KB | 13.3 KB | 5.7 KB | 24.7 KB | 67.0 KB | 1.6 KB |
| script time during page load | 8.1 ms | 9.7 ms | 8.4 ms | 10.2 ms | 17.9 ms | 7.6 ms |
| JS heap after load | 1.72 MB | 1.80 MB | 1.73 MB | 1.94 MB | 2.17 MB | 1.71 MB |
| JS heap with 1,000 rows | 2.33 MB | 3.24 MB | 2.96 MB | 4.10 MB | 4.52 MB | 2.11 MB |
| create rows | 32.0 ms | 33.6 ms | 33.1 ms | 38.9 ms | 41.1 ms | 32.2 ms |
| replace all rows | 35.4 ms | 38.9 ms | 39.1 ms | 42.9 ms | 47.0 ms | 35.3 ms |
| partial update (4× CPU slowdown) | 19.8 ms | 20.2 ms | 19.9 ms | 23.4 ms | 23.0 ms | 17.3 ms |
| select row (4× CPU slowdown) | 4.5 ms | 6.8 ms | 4.5 ms | 5.6 ms | 6.4 ms | 4.5 ms |
| swap rows (4× CPU slowdown) | 22.9 ms | 22.0 ms | 23.2 ms | 23.9 ms | 159 ms | 20.1 ms |
| remove row (2× CPU slowdown) | 15.6 ms | 16.0 ms | 16.3 ms | 18.8 ms | 17.2 ms | 15.8 ms |
| create many rows | 345 ms | 355 ms | 351 ms | 381 ms | 521 ms | 331 ms |
| append rows (2× CPU slowdown) | 83.0 ms | 85.3 ms | 84.4 ms | 88.6 ms | 93.7 ms | 81.9 ms |
| clear rows (4× CPU slowdown) | 15.1 ms | 17.0 ms | 17.7 ms | 21.4 ms | 23.3 ms | 14.5 ms |
HTMS has the lowest overall time of the frameworks tested (1.04× vanilla JS). Its scripting time is lowest or tied for lowest on 9 of 9 operations (scripting table). Rows where HTMS matches or beats each framework: Svelte 5 13 of 14, Solid 14 of 14, Vue 14 of 14, React 14 of 14. Bold marks the best framework in each row; vanilla JS is the hand-written reference. Chromium 141.0.7390.37 on Apple M2 Max, median of 15 runs, measured 2026-10-24. Full tables are in bench/results/RESULTS.md; the method and caveats are in bench/README.md.
The current toolchain requires Node 20.19 or newer.
npm ci
npm run build
npm run htms -- create click-counter
npm run htms -- dev click-counter.htmlOpen http://127.0.0.1:5173/, click the button, then edit the HTML. The browser reloads after a clean compile. If you misspell a tag or forget an attribute, the error appears in the preview and the terminal with the source line and a suggested fix.
The starter is deliberately small enough to pull apart. HTMS won't replace an existing file unless you pass --force.
Open the editable component playground, read the
getting-started guide,
or run npm run demo:serve and open http://localhost:5173/demos/.
Add htms() from htms/vite to your Vite plugins, then import a component
with import './click-counter.html?htms'. Vite compiles it and registers the
custom element during development and production builds. Ordinary HTML,
?raw and ?url imports keep their usual behavior.
Saving a component reloads the page, and compiler errors appear in Vite's overlay. See the Vite setup for configuration and TypeScript imports.
htms create <name>makes an interactive starter.htms newis an alias.htms dev <file>compiles, serves a preview and reloads it on save.htms validate <file>runs the real compiler without writing output.htms compile <file>writes JavaScript and a sibling TypeScript declaration.htms watch <file>recompiles without starting a server.htms render <file>produces server-rendered Declarative Shadow DOM.
Run htms <command> --help for every option. If a file declares several components, pass --tag <name> to dev or render. compile, watch and dev accept --renderer legacy to use the reconciling renderer instead of fine-grained blocks.
Attributes such as condition, expr, when and on:click, plus {...} in markup, are JavaScript expressions evaluated against the component. Name a prop, <var>, <derive> or <function> directly; the compiler turns count into this.count. Loop variables, event, locals you declare and globals (Math, Date, JSON) keep their usual meaning, and writing this.count still works.
<var name="items" value='[{"name": "Tea", "price": 3.5}]'></var>
<var name="rate" value="1.1"></var>
<p>{items.length} items, total {items.reduce((sum, item) => sum + item.price, 0) * rate}</p>
<p if="items.length === 0">Nothing here yet.</p>{user.name}is null-safe: it renders nothing whileuseris still loading, rather than failing the render.- Braces only interpolate when the expression reads a component field, a loop variable or
this. CSS blocks and literal text such as{ braces }are left alone. value="..."on<var>,<set>and<push>is a literal:'text',42,true,null, JSON, or the name of a field. Any other bare word is a string, sovalue="done"sets"done". Useexpr="..."for anything computed.
Markup elements accept directive attributes. They compile to the same listeners and properties as the directive tags and survive re-renders the same way.
| Attribute | Effect |
|---|---|
on:click="count++" or @click="..." |
Runs statements on the event. event is available. The component re-renders afterwards, so items.push(x) shows up. |
on:submit.prevent, .stop, .once, .passive, .capture, .self |
Event modifiers. |
on:keydown.enter, .esc, .space, .tab, .up/.down/.left/.right |
Key filters for keyboard events. |
on:input.debounce-250 |
Debounces the handler (.debounce alone means 300 ms). |
bind:value="name" |
Two-way binding. Also bind:checked, bind:valueasnumber, bind:selectedindex and bind:open. Number and range inputs store numbers. |
class:done="todo.done" |
Adds the class while the expression is truthy. |
style:width="pct + '%'" |
Sets an inline style property; null or false removes it. |
if="error" |
Renders the element only while the expression is truthy. |
<component name="todo-list">
<var name="todos" value="[]" mutable="true"></var>
<var name="draft" value="''" mutable="true"></var>
<form on:submit.prevent="todos.push({ text: draft, done: false }); draft = ''">
<input bind:value="draft" placeholder="Add a task">
</form>
<ul>
<repeat variable="todos" item="todo" index="i">
<li class:done="todo.done">
<input type="checkbox" bind:checked="todo.done"> {todo.text}
<button on:click="todos.splice(i, 1)">Remove</button>
</li>
</repeat>
</ul>
</component>HTML lowercases attribute names, so custom events used with on: should be kebab-case (on:item-selected). Native onclick attributes remain blocked; the browser would run them outside HTMS.
<function> inside a component becomes a method. The body can mix JavaScript and HTMS tags, params become arguments, and the component re-renders when the method returns.
<function name="add" params="text">
if (!text.trim()) return;
todos.push({ id: Date.now(), text: text.trim(), done: false });
</function>
<button on:click="add(draft)">Add</button>
<p>{format(total)}</p>Use async="true" for methods that await. Every component also has $(selector) and $$(selector) to query its own render root, plus emit(name, detail) to dispatch a composed CustomEvent.
<component> can expose browser-native custom element inputs:
<component
name="user-badge"
props="labelText, count:number, active:boolean, options:json"
>
<span id="label"></span>
<bind selector="#label" prop="textContent" expr="this.labelText"></bind>
</component>propscreates public properties with reactive setters. A prop is a string unless its name ends with:number,:boolean, or:json.- Props initialize from their matching kebab-case attributes (
labelTextreadslabel-text) and default tonullwhen no attribute is present. - Declared props automatically observe their matching attributes. Boolean props use attribute presence, invalid numbers and JSON become
null, and a missing boolean attribute becomesfalse. observedcan list extra attributes that aren't declared as props. Those are exposed as camel-cased string properties.
--format esm exports all generated classes in one ESM export list. --format cjs writes them to module.exports. --format iife registers the elements immediately and exposes the classes on globalThis.HTMSComponents.
Every format also gets a .d.ts file describing component props, emitted events, update lifecycle, and HTMLElementTagNameMap entries.
Prop changes and top-level state changes are batched into one render per microtask. An event handler can update several fields without rebuilding the component after every write.
Every generated component has requestUpdate() and updateComplete:
counter.count = 2;
counter.count = 3;
await counter.updateComplete;The DOM now contains the state for 3, after one render. Assigning a new value to a field declared with <var> schedules an update. JavaScript can't observe an in-place nested mutation such as counter.items.push(value), so call counter.requestUpdate() after that kind of change. HTMS <push> and <splice> do this automatically.
The compiler turns markup into blocks: a static template cloned once per instance, references to the nodes that can change, and an update method that re-evaluates each {expression} and binding and writes to the DOM only when its value changed. An update never rebuilds or diffs markup, so nodes keep their identity, keyboard focus, text selection, scroll position, and unfinished values in uncontrolled form fields. Fields managed by bind:value, <bind>, <model>, or <setprop> use their component state as the source of truth.
Derived calculations such as items.map(item => item.price) and
prices.reduce((sum, price) => sum + price, 0) keep their previous result
when unrelated state changes. The compiler follows their dependencies,
including derived chains and nested writes. Calculations with unknown calls
or side effects still run on each render; requestUpdate() forces all
derived values to recalculate.
Lists reuse rows by position, or by identity when the loop has a key:
<repeat variable="todos" item="todo" key="todo.id">
<li class:done="todo.done">{todo.text}</li>
</repeat>Keyed rows are matched by key and moved with as few DOM moves as possible (a longest-increasing-subsequence pass), so reordering, inserting and removing rows never recreates the rows that stay. A row that still holds the same item object keeps its place without evaluating the key, and a render that changed no order allocates nothing for the list. Event handlers in a component share one listener per event type on the component root.
A component that needs a feature the block renderer does not handle (<while>, or a directive selector that could match markup a loop creates) is compiled with the previous renderer, which builds a fragment on each render and reconciles it with the DOM. Pass renderer: 'legacy' to parseHTML to choose that renderer explicitly.
If a render fails, the component stores the error in renderError and emits a bubbling, composed htms-error event. Call event.preventDefault() after handling the error to suppress the default console report.
The server API renders compiled components in an isolated JSDOM document and returns Declarative Shadow DOM plus a JSON hydration manifest:
import { renderToString } from 'htms';
const { html } = renderToString(source, {
tagName: 'user-badge',
props: { labelText: 'Ready', count: 2 },
});The CLI exposes the same path:
htms render component.html \
--props '{"labelText":"Ready","count":2}' \
--attributes '{"class":"compact"}' \
--output component.ssr.html<effect> and <fetch> stay dormant on the server. In the browser, load the compiled component bundle and call hydrate() from the package. The first client render adopts the server tree in place, including a fallback for parsers that leave Declarative Shadow DOM as a template. Loop and branch content is marked with <!--[--> and <!--]--> comments in the server output and re-created on hydration; the surrounding markup keeps its server-rendered nodes.
- Parses HTMS markup with parse5 into a light source tree, converts nodes to directives via tag handlers, resolves component fields in expressions, validates the output with Meriyah, then emits JavaScript through Escodegen.
- A security pass rejects dangerous constructs (
eval, inline handlers, rawinnerHTML, path traversal, …). - In component mode, standard elements become cached
<template>fragments that each instance clones. Control and state tags compile into block methods that update only the nodes whose values changed. - Directive selectors such as
<event target="#save">and<bind selector="#count">are resolved at compile time against the template, so they cost nothing at runtime. - Directives work inside tables:
<tbody><repeat ...><tr>…</tr></repeat></tbody>keeps the rows where they are written instead of letting the HTML parser move them out of the table. - Component text and attributes can interpolate reactive state and props with
{count},{user.name}, and{labelText}. - Components compose through normal custom elements and browser slots. Dynamic SVG and MathML nodes keep their namespaces.
- Component-owned runtime effects are disposed in
disconnectedCallback, so cleanup handlers and fetch aborts run when elements leave the page. - Effect and fetch helpers share one runtime bootstrap per generated bundle. Components that do not use runtime-backed directives do not include it.
- Server and client rendering use the same component compiler and generated code.
- State & Arrays
<var name="x" value="42" mutable="true" />— declare component state (accepts quoted strings, numbers, booleans and JSON, including arrays of objects).<object name="user">…<property name="name" value="Ada" /></object>and<array name="tags"><value>a</value></array>— declare object/array state from child tags.<derive name="total" expr="this.items.length" />— compute reactive state before rendering, reusing known pure results while their dependencies stay unchanged.<set name="x" op="=|+=|-=|*=|/=|++|--" value="…" />orexpr="…"— mutate values; notifies bindings.+=concatenates strings.<push array="state.list" expr="document.getElementById('txt').value" />— push; notifies bindings.<splice array="state.list" index="0" delete="1" values='["New"]' />— remove/insert; notifies bindings.
- Control Flow
<repeat variable="items" item="it" index="i">…</repeat>or<repeat count="3" index="n">…</repeat>(countmay be an expression such ascount="rating") —itemnames the loop variable (defaultitem); inside, use{it}, property paths like{it.name}, and the optional index token ({i}here) in text or attribute values. Addkey="it.id"to keep each row's DOM nodes when the array is reordered.<if condition="flag">…</if><else-if condition="other">…</else-if><else>…</else>— nested tags allowed.<while condition="state.count < 3" max="1000">…</while>— guarded loop;maxprevents infinite loops.<switch variable="day">…</switch>or<switch expr="this.day">…</switch>— nested tags allowed.
- DOM Updates
<setprop selector="#msg" prop="textContent" expr="'Hello'" />— set property (useexprfor JS, orvaluefor literals).<setattr selector="#link" name="title" value="Info" />— set attribute.expr="…"computes it;null/falseremoves it.<append target="#list"> <li>Row</li> </append>— append generated children to an existing element.<class selector="#card" name="active" when="this.isActive" />— toggle class based on expression.<style selector="#card" prop="background-color" value="red" />— set inline style.<model selector="#name" path="name" />— two-way input binding (value+inputevent). Addnumber="true"to store numbers.bind:valueon the input is the inline equivalent.
- Visibility
<toggle target="#panel" condition="isOpen" />— show/hide (style.display).<show target="#a" when="x > 5" />— sugar over TOGGLE.
- Reactive Bindings
<bind selector="#cnt" prop="textContent" expr="String(state.items.length)" />— binds DOM to an expression; updates on SET/PUSH/SPLICE.- Native component markup can also bind directly:
<p title="Count {count}">{label}: {count}</p>. - Interpolating a boolean attribute (
disabled,checked,readonly, …) toggles the attribute's presence instead of rendering"true"/"false"strings:<button disabled="{submitting}">. - HTMS directives nest inside ordinary markup, scoped to the enclosing element:
<div><event target="#btn" type="click">…</event></div>works without a top-level<event>.
- Lists (keyed)
<keyedlist target="#ul" of="items" item="it" index="i" key="it.id"> <li>{it.name}</li> </keyedlist>— component-scoped keyed list rendering with item/index interpolation and DOM node preservation for matching keys.
- Composition
- Put one compiled custom element inside another as normal HTML. The compiler keeps custom-element children instead of treating them as unknown HTMS tags.
- Use
<slot></slot>and<slot name="heading"></slot>inside a component to accept default and named content from its parent. - SVG and MathML can sit directly in a component template, including interpolated attributes.
- Events
<event target="#btn" type="click"> …child tags… </event>— handler is composed of child tags (no action string required).typeaccepts any DOM event name, including custom events dispatched by<emit>.target="window","document"or":host"listen outside the render root and detach with the component.- Event modifiers:
prevent="true"callsevent.preventDefault(),stop="true"callsevent.stopPropagation(),self="true"ignores events from descendants,once="true"removes the listener after the first fire (it stays fired across re-renders),passive="false"marks the listener non-passive,key="Enter"filtersKeyboardEvents, anddebounce="200"delays the handler by N milliseconds.<event>tags can nest inside ordinary markup — they bind relative to the enclosing element. <submit target="#form"> …child tags… </submit>— form submit helper (prevents default). Use child tags to update state/DOM.<emit name="count-changed" detail="this.count" />— dispatches aCustomEventfrom the component so parents can react. Place it inside an<event>/<submit>handler. Defaults tobubbles/composedso the event crosses the shadow boundary; opt out withbubbles="false"/composed="false", or setcancelable="true".
Run npm run demo:serve, then open http://localhost:5173/demos/.
Choose an example in the editor or click a gallery card. Edit the HTMS source
and press Compile & preview (or Ctrl/⌘ + Enter). Each successful compile
starts a fresh preview, so you can redefine the same component repeatedly.
For files with several components, use the preview selector to choose which
one to mount. Expand Generated JavaScript to inspect the compiler output.
Errors and warnings appear below the editor with the compiler's original message, tag, source line and column, and hint when available. Click a source location to move the cursor there. Diagnostics about generated JavaScript are labelled separately and don't point into the HTML source. Editing clears the previous result; failed compiles never run partial output.
Switching examples keeps your edits for this visit. Reset example restores
the selected example, and reloading the page discards all drafts. A link such as
http://localhost:5173/demos/#example=counter-component selects an example;
it doesn't contain or share your edits.
Compilation runs locally in a Web Worker using the same strict compiler as the
CLI. The playground limits input to 256 KiB and stops compilation after ten
seconds. Stop removes the running preview. Preview code runs in an iframe
with sandbox="allow-scripts", without access to the gallery's DOM or storage.
Its content policy blocks fetch, external resources, nested frames and form
submission; links are disabled. Fetch examples therefore show blocked requests
here. The sandbox is not a CPU or memory quota: pathological preview code can
still make a browser tab unresponsive.
npm run demo:build regenerates the static gallery, original standalone
*.preview.html pages, and local editor/compiler bundles. It needs no CDN or
compilation API and works under a static host's subdirectory, including GitHub
Pages. The standalone pages still run the checked-in examples without the
editor's sandbox restrictions. Edit scripts/playground.html and
scripts/playground.css for the editor layout, or src/playground/ for its
behavior; don't edit the generated bundles. Run npm test -- tests/playground.spec.ts
for diagnostic/preview tests and npm run test:e2e for browser checks (including
the playground); Playwright builds and serves the demos automatically.
demos/hello-world-component.html— minimal “hello” rendered via shadow DOM.demos/event-toggle-component.html—<event>,<setattr>, and<toggle>working together.demos/bind-component.html—<bind>hydrates text content without global state.demos/counter-component.html—<var>,<set>, and<bind>demonstrate reactive state and re-rendering.demos/derived-component.html— derived values update before template interpolation and bindings.demos/emit-component.html—<emit>dispatches a composedCustomEventto the host so parents can listen.demos/composition-component.html— two compiled components composed with named and default slots.demos/ssr-card-component.html— typed props rendered on the server and updated through a client event.demos/list-component.htmlanddemos/todo-component.html— repeat rendering, keyed updates, item events, and form state.demos/effect-fetch-component.html,demos/effect-fetch-error-component.html, anddemos/effect-fetch-auto-component.html— request success, failure, cleanup, and automatic loading.
HTMS rejects known executable sinks and unsafe template attributes, but source files are still application code. Do not execute compiled untrusted markup in your application's page. The demo editor uses a separate sandboxed iframe with a restrictive content policy for previews; the compiler alone is not that security boundary.
<inject>is disabled entirely unlessHTMS_ALLOW_INJECT_TAG=trueis set — and even then it writes throughtextContent, neverinnerHTML.- Inline event-handler attributes (
onclick,onload, …) are rejected in markup; useon:clickor<event>instead. - Dynamic URL attributes (
href="{link}",<setattr name="src" expr="…">) are checked when they render.javascript:,vbscript:anddata:text/htmlvalues becomeabout:blank. - File logging is opt-in: set
HTMS_LOG_DIRto writehtms-combined.log/htms-error.logto a chosen directory. Importing the library never writes files to your working directory.