Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

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

License

NotificationsYou must be signed in to change notification settings

developit/htm

Repository files navigation

hyperscript tagged markup demo

htm isJSX-like syntax in plain JavaScript - no transpiler necessary.

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

It uses standard JavaScriptTagged Templates and works inall modern browsers.

htm by the numbers:

🐣< 600 bytes when used directly in the browser

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

🥚< 450 bytehtm/mini version

🏅0 bytes if compiled usingbabel-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>(whereFoo 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 thelit-html VSCode extension andvim-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:

npmihtm

hotlinking from unpkg:(no build tool needed!)

importhtmfrom'https://unpkg.com/htm?module'consthtml=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`<ahref="/">Hello!</a>`,document.body);

Similarly, for React:

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

Advanced Usage

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

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

functionh(type,props, ...children){return{ type, props, children};}

To use our customh() function, we need to create our ownhtml tag function by bindinghtm to ourh() function:

importhtmfrom'htm';consthtml=htm.bind(h);

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

Here's the whole thing for clarity:

importhtmfrom'htm';functionh(type,props, ...children){return{ type, props, children};}consthtml=htm.bind(h);console.log(html`<h1id=hello>Hello world!</h1>`);// {//   type: 'h1',//   props: { id: 'hello' },//   children: ['Hello world!']// }

If the template has multiple element at the root levelthe output is an array ofh results:

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

Caching

The default build ofhtm 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 yourh function to copy nodes when needed.
  • Add the codethis[0] = 3; at the beginning of yourh function, which disables caching of created elements.
  • Usehtm/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><htmllang="en"><title>htm Demo</title><scripttype="module">import{html,Component,render}from'https://unpkg.com/htm/preact/standalone.module.js';classAppextendsComponent{addTodo(){const{ todos=[]}=this.state;this.setState({todos:todos.concat(`Item${todos.length}`)});}render({ page},{ todos=[]}){returnhtml`<divclass="app"><${Header}name="ToDo's (${page})"/><ul>${todos.map(todo=>html`<likey=${todo}>${todo}</li>              `)}</ul><buttononClick=${()=>this.addTodo()}>Add Todo</button><${Footer}>footer content here<//></div>        `;}}constHeader=({ name})=>html`<h1>${name} List</h1>`constFooter=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';importhtmfrom'htm';consthtml=htm.bind(h);render(html`<${App}page="All"/>`,document.body);

Other Uses

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

Generate HTML usingvhtml:

importhtmfrom'htm';importvhtmlfrom'vhtml';consthtml=htm.bind(vhtml);console.log(html`<h1id=hello>Hello world!</h1>`);// '<h1>Hello world!</h1>'

Webpack configuration viajsxobj: (details here)(never do this)

importhtmfrom'htm';importjsxobjfrom'jsxobj';consthtml=htm.bind(jsxobj);console.log(html`<webpackwatchmode=production><entrypath="src/index.js"/></webpack>`);// {//   watch: true,//   mode: 'production',//   entry: {//     path: 'src/index.js'//   }// }

Demos & Examples

Project Status

The original goal forhtm 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 wasTagged 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.

About

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

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp