Convert Figma logo to code with AI

developit logohtm

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

8,695
170
8,695
42

Top Related Projects

36,546

⚛️ Fast 3kB React alternative with the same modern API. Components & Virtual DOM.

227,213

The library for web and native user interfaces.

207,677

This is the repo for Vue 2. For Vue 3, go to https://github.com/vuejs/core

78,194

Cybernetically enhanced web apps

27,910

A rugged, minimal framework for composing JavaScript behavior in your markup.

18,486

Lit is a simple library for building fast, lightweight web components.

Quick Overview

HTM (Hyperscript Tagged Markup) is a JSX-like syntax for creating virtual DOM trees using tagged template literals in JavaScript. It allows developers to write HTML-like code within JavaScript without the need for a transpilation step, making it a lightweight alternative to JSX for use with frameworks like Preact or vanilla JavaScript.

Pros

  • No build step required, works natively in modern browsers
  • Lightweight and fast, with minimal overhead
  • Seamless integration with JavaScript, allowing for dynamic expressions
  • Compatible with various virtual DOM libraries, including Preact and React

Cons

  • Less widespread adoption compared to JSX
  • Limited tooling support (e.g., syntax highlighting) in some IDEs
  • Potential for decreased readability in complex nested structures
  • Slight runtime performance overhead compared to pre-compiled JSX

Code Examples

Creating a simple element:

import { html } from 'htm/preact';

const element = html`<div>Hello, world!</div>`;

Rendering a component with props:

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

const Greeting = ({ name }) => html`<h1>Hello, ${name}!</h1>`;

render(html`<${Greeting} name="Alice" />`, document.body);

Using conditional rendering and loops:

import { html } from 'htm/preact';

const List = ({ items }) => html`
  <ul>
    ${items.map(item => html`
      <li>${item.name} ${item.completed ? '✓' : '❌'}</li>
    `)}
  </ul>
`;

Getting Started

To use HTM with Preact, follow these steps:

  1. Install the required packages:

    npm install htm preact
    
  2. Create a new JavaScript file (e.g., app.js) and add the following code:

    import { html, render } from 'htm/preact';
    
    const App = () => html`
      <div>
        <h1>Hello HTM!</h1>
        <p>Welcome to your first HTM application.</p>
      </div>
    `;
    
    render(html`<${App} />`, document.body);
    
  3. Include the script in your HTML file and run it in a modern browser or using a development server.

Competitor Comparisons

36,546

⚛️ Fast 3kB React alternative with the same modern API. Components & Virtual DOM.

Pros of Preact

  • Smaller bundle size and faster performance compared to React
  • Full compatibility with React ecosystem through preact/compat
  • Virtual DOM implementation for efficient updates

Cons of Preact

  • Smaller community and ecosystem compared to React
  • Some advanced React features may not be available or require additional setup
  • Learning curve for developers transitioning from React

Code Comparison

Preact:

import { h, render } from 'preact';

const App = () => <h1>Hello, World!</h1>;
render(<App />, document.body);

HTM:

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

const App = () => html`<h1>Hello, World!</h1>`;
render(App(), document.body);

Key Differences

  • HTM uses tagged template literals for JSX-like syntax without a build step
  • Preact requires a build step for JSX compilation
  • HTM can be used with various view libraries, while Preact is a standalone framework
  • Preact offers a more complete React-like experience, while HTM focuses on lightweight templating

Use Cases

  • Preact: Ideal for building full-fledged web applications with React-like architecture
  • HTM: Suitable for smaller projects or when avoiding build tools is preferred

Community and Ecosystem

  • Preact has a larger community and more third-party libraries
  • HTM is more focused and has fewer resources, but is actively maintained
227,213

The library for web and native user interfaces.

Pros of React

  • Extensive ecosystem with a wide range of libraries and tools
  • Strong community support and frequent updates
  • Robust performance optimization features like virtual DOM

Cons of React

  • Steeper learning curve, especially for beginners
  • Larger bundle size compared to HTM
  • More complex setup and configuration

Code Comparison

React:

import React from 'react';

function Greeting({ name }) {
  return <h1>Hello, {name}!</h1>;
}

HTM:

import { html } from 'htm/preact';

const Greeting = ({ name }) => html`
  <h1>Hello, ${name}!</h1>
`;

Key Differences

  • HTM uses template literals, while React uses JSX
  • HTM has a smaller footprint and simpler setup
  • React offers more advanced features and better performance for large applications
  • HTM provides a more lightweight solution for smaller projects or quick prototyping

Use Cases

  • Choose React for complex, large-scale applications with high performance requirements
  • Opt for HTM when you need a simple, lightweight solution or want to avoid build steps

Both libraries have their strengths, and the choice depends on project requirements and developer preferences.

207,677

This is the repo for Vue 2. For Vue 3, go to https://github.com/vuejs/core

Pros of Vue

  • Comprehensive framework with a full ecosystem (Vue Router, Vuex, Vue CLI)
  • Extensive documentation and large community support
  • Gentle learning curve for beginners

Cons of Vue

  • Larger bundle size compared to HTM
  • More opinionated structure, which may be limiting for some projects
  • Requires compilation step for optimal performance

Code Comparison

Vue:

<template>
  <div>
    <h1>{{ title }}</h1>
    <button @click="increment">Count: {{ count }}</button>
  </div>
</template>

<script>
export default {
  data() {
    return { count: 0, title: 'Vue Example' }
  },
  methods: {
    increment() { this.count++ }
  }
}
</script>

HTM:

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

const App = () => {
  const [count, setCount] = useState(0);
  return html`
    <div>
      <h1>HTM Example</h1>
      <button onClick=${() => setCount(count + 1)}>Count: ${count}</button>
    </div>
  `;
};

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

HTM offers a lighter-weight solution with no build step required, while Vue provides a more structured and feature-rich development experience. The choice between them depends on project requirements and developer preferences.

78,194

Cybernetically enhanced web apps

Pros of Svelte

  • Offers a complete framework with built-in state management and reactivity
  • Compiles to highly optimized vanilla JavaScript, resulting in smaller bundle sizes
  • Provides a more intuitive and less boilerplate-heavy syntax for building components

Cons of Svelte

  • Requires a build step, which can add complexity to the development process
  • Has a smaller ecosystem and community compared to more established frameworks
  • Learning curve may be steeper for developers accustomed to traditional frameworks

Code Comparison

Svelte component:

<script>
  let count = 0;
  function increment() {
    count += 1;
  }
</script>

<button on:click={increment}>
  Clicks: {count}
</button>

HTM component:

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

class Counter extends Component {
  state = { count: 0 };
  increment = () => this.setState({ count: this.state.count + 1 });
  render() {
    return html`
      <button onClick=${this.increment}>
        Clicks: ${this.state.count}
      </button>
    `;
  }
}

Both Svelte and HTM offer ways to create reactive UI components, but Svelte's approach is more concise and requires less boilerplate. HTM, on the other hand, provides a lightweight solution for using JSX-like syntax without a build step, making it easier to integrate into existing projects.

27,910

A rugged, minimal framework for composing JavaScript behavior in your markup.

Pros of Alpine

  • Lightweight and easy to learn, with a gentle learning curve
  • Integrates seamlessly with existing HTML, requiring minimal changes
  • Offers a comprehensive set of directives for common UI interactions

Cons of Alpine

  • Limited to DOM manipulation and basic interactivity
  • May become unwieldy for large, complex applications
  • Lacks advanced features like virtual DOM or component-based architecture

Code Comparison

Alpine:

<div x-data="{ open: false }">
    <button @click="open = !open">Toggle</button>
    <span x-show="open">Content</span>
</div>

HTM:

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

const App = ({ open }) => html`
  <div>
    <button onClick=${() => setOpen(!open)}>Toggle</button>
    ${open && html`<span>Content</span>`}
  </div>
`;

render(html`<${App} open=${false} />`, document.body);

Alpine focuses on enhancing existing HTML with directives, while HTM uses a template literal syntax to create components. Alpine is more suited for adding interactivity to static HTML, whereas HTM is better for building component-based applications with a virtual DOM.

18,486

Lit is a simple library for building fast, lightweight web components.

Pros of lit

  • More comprehensive framework with additional features like reactive properties and lifecycle callbacks
  • Better performance for complex applications due to its efficient rendering system
  • Larger community and ecosystem, with more resources and third-party libraries available

Cons of lit

  • Steeper learning curve compared to htm's simplicity
  • Larger bundle size, which may impact load times for smaller applications
  • More opinionated approach, potentially limiting flexibility in some scenarios

Code Comparison

htm:

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

const App = ({ name }) => html`
  <h1>Hello ${name}!</h1>
`;

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

lit:

import { LitElement, html } from 'lit';

class MyElement extends LitElement {
  static properties = { name: {} };
  render() {
    return html`<h1>Hello ${this.name}!</h1>`;
  }
}
customElements.define('my-element', MyElement);

Both htm and lit provide ways to create web components using template literals, but lit offers a more structured approach with its LitElement base class and property system. htm focuses on simplicity and flexibility, while lit provides a more comprehensive framework for building complex applications.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

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

Installation

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

via npm:

npm i htm

hotlinking from unpkg: (no build tool needed!)

import htm from 'https://unpkg.com/htm?module'
const html = htm.bind(React.createElement);
// just want htm + preact in a single file? there's a highly-optimized version of that:
import { html, render } from 'https://unpkg.com/htm/preact/standalone.module.js'

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="module">
    import { html, Component, render } from 'https://unpkg.com/htm/preact/standalone.module.js';

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

NPM DownloadsLast 30 Days