HTM

Hyperscript Tagged Markup: JSX alternative using standard tagged templates,...

README


  HTM (Hyperscript Tagged Markup)
npm

hyperscript tagged markup demo


htm is JSX-like syntax in plain JavaScript - 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:


🐣 < 600 bytes when used directly in the browser

⚛️ < 500 bytes when used with Preact _(thanks gzip 🌈)_

🥚 < 450 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: `
` instead of `
`- Self-closing tags: `
`- Components: `<${Foo}>` instead of `` _(where `Foo` is a component reference)_- Boolean attributes: `
`


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: `
`- 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): `
`- Support for HTML-style comments: `
`

Installation


htm is published to npm, and accessible via the unpkg.com CDN:

via npm:

  1. ``` js
  2. npm i htm
  3. ```

hotlinking from unpkg: _(no build tool needed!)_

  1. ``` js
  2. import htm from 'https://unpkg.com/htm?module'
  3. const html = htm.bind(React.createElement);
  4. ```

  1. ``` js
  2. // just want htm + preact in a single file? there's a highly-optimized version of that:
  3. import { html, render } from 'https://unpkg.com/htm/preact/standalone.module.js'
  4. ```

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.

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

Similarly, for React:

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

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:

  1. ``` js
  2. function h(type, props, ...children) {
  3.   return { type, props, children };
  4. }
  5. ```

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

  1. ``` js
  2. import htm from 'htm';

  3. const html = htm.bind(h);
  4. ```

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:

  1. ``` js
  2. import htm from 'htm';

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

  6. const html = htm.bind(h);

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

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

  1. ``` js
  2. console.log(html`
  3.   <h1 id=hello>Hello</h1>
  4.   <div class=world>World!</div>
  5. `);
  6. // [
  7. //   {
  8. //     type: 'h1',
  9. //     props: { id: 'hello' },
  10. //     children: ['Hello']
  11. //   },
  12. //   {
  13. //     type: 'div',
  14. //     props: { class: 'world' },
  15. //     children: ['world!']
  16. //   }
  17. // ]
  18. ```

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.

  1. ``` html
  2. <!DOCTYPE html>
  3. <html lang="en">
  4.   <title>htm Demo</title>
  5.   <script type="module">
  6.     import { html, Component, render } from 'https://unpkg.com/htm/preact/standalone.module.js';
  7.     class App extends Component {
  8.       addTodo() {
  9.         const { todos = [] } = this.state;
  10.         this.setState({ todos: todos.concat(`Item ${todos.length}`) });
  11.       }
  12.       render({ page }, { todos = [] }) {
  13.         return html`
  14.           <div class="app">
  15.             ${Header} name="ToDo's (${page})" />
  16.             <ul>
  17.               ${todos.map(todo => html`
  18.                 <li key=${todo}>${todo}</li>
  19.               `)}
  20.             </ul>
  21.             <button onClick=${() => this.addTodo()}Add Todo</button>
  22.             ${Footer}>footer content here<//>
  23.           </div>
  24.         `;
  25.       }
  26.     }
  27.     const Header = ({ name }) = html`<h1>${name} List</h1>`
  28.     const Footer = props = html`<footer ...${props} />`
  29.     render(html`${App} page="All" />`, document.body);
  30.   </script>
  31. </html>
  32. ```

[⚡️ See live version ▶](https://htm-demo-preact.glitch.me/)

[⚡️ Try this on CodeSandbox ▶](https://codesandbox.io/s/x7pmq32j6q)

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:

  1. ``` js
  2. import { h, Component, render } from 'preact';
  3. import htm from 'htm';

  4. const html = htm.bind(h);

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

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]:

  1. ``` js
  2. import htm from 'htm';
  3. import vhtml from 'vhtml';

  4. const html = htm.bind(vhtml);

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

    Hello world!

    '
  7. ```

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

  1. ``` js
  2. import htm from 'htm';
  3. import jsxobj from 'jsxobj';

  4. const html = htm.bind(jsxobj);

  5. console.log(html`
  6.   <webpack watch mode=production>
  7.     <entry path="src/index.js" />
  8.   </webpack>
  9. `);
  10. // {
  11. //   watch: true,
  12. //   mode: 'production',
  13. //   entry: {
  14. //     path: 'src/index.js'
  15. //   }
  16. // }
  17. ```

Demos & Examples


- Canadian Holidays: A full app using HTM and Server-Side Rendering
- HTM SSR Example: Shows how to do SSR with HTM

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 is stable, fast, well-tested and ready for production use.

[Tagged Templates]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_templates
[lit-html]: https://github.com/Polymer/lit-html
[babel-plugin-htm]: https://github.com/developit/htm/tree/master/packages/babel-plugin-htm
[lit-html VSCode extension]: https://marketplace.visualstudio.com/items?itemName=bierner.lit-html
[vim-jsx-pretty plugin]: https://github.com/MaxMEllon/vim-jsx-pretty
[vhtml]: https://github.com/developit/vhtml
[jsxobj]: https://github.com/developit/jsxobj
[hyperscript]: https://github.com/hyperhype/hyperscript
[all modern browsers]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Browser_compatibility