extremeheat/htm-plus

HTM+: JSX alternative using standard tagged templates, with compiler support.

★ 0Forks 0JavaScriptGitHub ↗Compare

README

hyperscript tagged markup demo

HTM+ is a fork of HTM with improved character-reference and Unicode handling. It provides JSX-like syntax in plain JavaScript with no transpiler necessary.

Develop with React/Preact directly in the browser, then compile htm away for production.

It uses standard JavaScript Tagged Templates and works in all modern browsers.

HTM+ by the numbers:

🐣 < 900 bytes when used directly in the browser

⚛️ Works directly with Preact through the included bindings

🥚 < 750 byte htm/mini version

🏅 0 bytes if compiled using babel-plugin-htm

Syntax: like JSX but also lit

The syntax you write when using HTM is as close as possible to JSX:

  • Spread props: <div ...${props}> instead of <div {...props}>
  • Self-closing tags: <div />
  • Components: <${Foo}> instead of <Foo> (where Foo is a component reference)
  • Boolean attributes: <div draggable />

Improvements over JSX

htm actually takes the JSX-style syntax a couple steps further!

Here's some ergonomic features you get for free that aren't present in JSX:

  • No transpiler necessary
  • HTML's optional quotes: <div class=foo>
  • Component end-tags: <${Footer}>footer content<//>
  • Syntax highlighting and language support via the lit-html VSCode extension and vim-jsx-pretty plugin.
  • Multiple root element (fragments): <div /><div />
  • Support for HTML-style comments: <div><!-- comment --></div>

Character references

Static HTM+ markup decodes the commonly used named references &amp;, &apos;, &gt;, &lt;, &nbsp; and &quot;. Decimal and hexadecimal numeric references are supported for all other Unicode characters:

html`<p>A&nbsp;space and a smile: &#x1F600;</p>`

References must end in a semicolon. Interpolated values are passed through unchanged, so ${'&nbsp;'} remains the literal string &nbsp;.

Installation

Until the first npm release, install HTM+ directly from its GitHub repository:

npm install github:extremeheat/htm-plus#main

The GitHub package currently retains the original htm package name, so its Node and bundler imports remain:

import htm from 'htm';
import { html } from 'htm/preact';

Browser import from GitHub

jsDelivr can serve the source modules directly from GitHub without a package release:

import htm from 'https://cdn.jsdelivr.net/gh/extremeheat/htm-plus@main/src/index.mjs';
const html = htm.bind(React.createElement);

Pin a release tag or commit instead of main for production deployments.

UNPKG serves packages from the npm registry, so unpkg.com/htm-plus will become available automatically after HTM+ is published to npm. No separate UNPKG registration is required.

Usage

If you're using Preact or React, we've included off-the-shelf bindings to make your life easier. They also have the added benefit of sharing a template cache across all modules.

import { render } from 'preact';
import { html } from 'htm/preact';
render(html`<a href="/">Hello!</a>`, document.body);

Similarly, for React:

import ReactDOM from 'react-dom';
import { html } from 'htm/react';
ReactDOM.render(html`<a href="/">Hello!</a>`, document.body);

Advanced Usage

Since htm is a generic library, we need to tell it what to "compile" our templates to. You can bind htm to any function of the form h(type, props, ...children) (hyperscript). This function can return anything - htm never looks at the return value.

Here's an example h() function that returns tree nodes:

function h(type, props, ...children) {
  return { type, props, children };
}

To use our custom h() function, we need to create our own html tag function by binding htm to our h() function:

import htm from 'htm';

const html = htm.bind(h);

Now we have an html() template tag that can be used to produce objects in the format we created above.

Here's the whole thing for clarity:

import htm from 'htm';

function h(type, props, ...children) {
  return { type, props, children };
}

const html = htm.bind(h);

console.log( html`<h1 id=hello>Hello world!</h1>` );
// {
//   type: 'h1',
//   props: { id: 'hello' },
//   children: ['Hello world!']
// }

If the template has multiple element at the root level the output is an array of h results:

console.log(html`
  <h1 id=hello>Hello</h1>
  <div class=world>World!</div>
`);
// [
//   {
//     type: 'h1',
//     props: { id: 'hello' },
//     children: ['Hello']
//   },
//   {
//     type: 'div',
//     props: { class: 'world' },
//     children: ['world!']
//   }
// ]

Caching

The default build of htm caches template strings, which means that it can return the same Javascript object at multiple points in the tree. If you don't want this behaviour, you have three options:

  • Change your h function to copy nodes when needed.
  • Add the code this[0] = 3; at the beginning of your h function, which disables caching of created elements.
  • Use htm/mini, which disables caching by default.

Example

Curious to see what it all looks like? Here's a working app!

It's a single HTML file, and there's no build or tooling. You can edit it with nano.

<!DOCTYPE html>
<html lang="en">
  <title>HTM+ Demo</title>
  <script type="importmap">
    {
      "imports": {
        "preact": "https://cdn.jsdelivr.net/npm/[email protected]/dist/preact.module.js",
        "preact/hooks": "https://cdn.jsdelivr.net/npm/[email protected]/hooks/dist/hooks.module.js"
      }
    }
  </script>
  <script type="module">
    import { html, Component, render } from 'https://cdn.jsdelivr.net/gh/extremeheat/htm-plus@main/src/integrations/preact/standalone.mjs';

    class App extends Component {
      addTodo() {
        const { todos = [] } = this.state;
        this.setState({ todos: todos.concat(`Item ${todos.length}`) });
      }
      render({ page }, { todos = [] }) {
        return html`
          <div class="app">
            <${Header} name="ToDo's (${page})" />
            <ul>
              ${todos.map(todo => html`
                <li key=${todo}>${todo}</li>
              `)}
            </ul>
            <button onClick=${() => this.addTodo()}>Add Todo</button>
            <${Footer}>footer content here<//>
          </div>
        `;
      }
    }

    const Header = ({ name }) => html`<h1>${name} List</h1>`

    const Footer = props => html`<footer ...${props} />`

    render(html`<${App} page="All" />`, document.body);
  </script>
</html>

⚡️ See live version ▶

⚡️ Try this on CodeSandbox ▶

How nifty is that?

Notice there's only one import - here we're using the prebuilt Preact integration since it's easier to import and a bit smaller.

The same example works fine without the prebuilt version, just using two imports:

import { h, Component, render } from 'preact';
import htm from 'htm';

const html = htm.bind(h);

render(html`<${App} page="All" />`, document.body);

Other Uses

Since htm is designed to meet the same need as JSX, you can use it anywhere you'd use JSX.

Generate HTML using vhtml:

import htm from 'htm';
import vhtml from 'vhtml';

const html = htm.bind(vhtml);

console.log( html`<h1 id=hello>Hello world!</h1>` );
// '<h1 id="hello">Hello world!</h1>'

Webpack configuration via jsxobj: (details here) (never do this)

import htm from 'htm';
import jsxobj from 'jsxobj';

const html = htm.bind(jsxobj);

console.log(html`
  <webpack watch mode=production>
    <entry path="src/index.js" />
  </webpack>
`);
// {
//   watch: true,
//   mode: 'production',
//   entry: {
//     path: 'src/index.js'
//   }
// }

Demos & Examples

Project Status

The original goal for htm was to create a wrapper around Preact that felt natural for use untranspiled in the browser. I wanted to use Virtual DOM, but I wanted to eschew build tooling and use ES Modules directly.

This meant giving up JSX, and the closest alternative was Tagged Templates. So, I wrote this library to patch up the differences between the two as much as possible. The technique turns out to be framework-agnostic, so it should work great with any library or renderer that works with JSX.

HTM+ retains HTM's stable, fast and well-tested core while developing its additional parsing and integration improvements.

See IMPROVEMENTS.md for completed changes, planned work and the compatibility policy for this fork.

Contributors

developitjviidemarvinhagemeisterblikblumstyfleextremeheatsurmavikermanSaraVieiramathiasbynensartisoniankristoferbaxteryulerspoerriziadkh0yhattWesleyACwight554SijmenHuizengazsergeschalkventersibbngSolarLinerxmonkeelmorchardyuezkJodiWarrendrjayveegrgurAlonski

Issues