• Stars
    star
    687
  • Rank 65,799 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🐉 HTML template strings for the Browser with support for Server Side Rendering in Node.

nanohtml

npm version build status downloads js-standard-style

HTML template strings for the Browser with support for Server Side Rendering in Node.

Installation

$ npm install nanohtml

Usage

Browser

var html = require('nanohtml')

var el = html`
  <body>
    <h1>Hello planet</h1>
  </body>
`

document.body.appendChild(el)

Node

Node doesn't have a DOM available. So in order to render HTML we use string concatenation instead. This has the fun benefit of being quite efficient, which in turn means it's great for server rendering!

var html = require('nanohtml')

var el = html`
  <body>
    <h1>Hello planet</h1>
  </body>
`

console.log(el.toString())

Node with custom DOM

Modules like jsdom implement (parts of) the DOM in pure JavaScript. If you don't really need the performance of string concatenation, or use nanohtml components that modify the raw DOM, use nanohtml/dom to give nanohtml a custom Document.

var JSDOM = require('jsdom').JSDOM
var nanohtml = require('nanohtml/dom')
var jsdom = new JSDOM()

var html = nanohtml(jsdom.window.document)
var el = html`
  <body>
    <h1>Hello planet</h1>
  </body>
`
el.appendChild(html`<p>A paragraph</p>`)

el.outerHTML === '<body><h1>Hello planet</h1><p>A paragraph</p></body>'

Interpolating unescaped HTML

By default all content inside template strings is escaped. This is great for strings, but not ideal if you want to insert HTML that's been returned from another function (for example: a markdown renderer). Use nanohtml/raw for to interpolate HTML directly.

var raw = require('nanohtml/raw')
var html = require('nanohtml')

var string = '<h1>This a regular string.</h1>'
var el = html`
  <body>
    ${raw(string)}
  </body>
`

document.body.appendChild(el)

Attaching event listeners

var html = require('nanohtml')

var el = html`
  <body>
    <button onclick=${onclick}>
      Click Me
    </button>
  </body>
`

document.body.appendChild(el)

function onclick (e) {
  console.log(`${e.target} was clicked`)
}

Multiple root elements

If you have more than one root element they will be combined with a DocumentFragment.

var html = require('nanohtml')

var el = html`
  <li>Chashu</li>
  <li>Nori</li>
`

document.querySelector('ul').appendChild(el)

Conditional attributes

Use a javascript object to conditionally add HTML attributes.

var html = require('nanohtml')

var customAttr = isFuzzy ? { 'data-hand-feel': 'super-fuzzy' } : {}
var el = html`
  <div ${ customAttr }></div>
`

Static optimizations

Parsing HTML has significant overhead. Being able to parse HTML statically, ahead of time can speed up rendering to be about twice as fast.

Browserify

From the command line

$ browserify -t nanohtml index.js > bundle.js

Programmatically

var browserify = require('browserify')
var nanohtml = require('nanohtml')
var path = require('path')

var b = browserify(path.join(__dirname, 'index.js'))
  .transform(nanohtml)

b.bundle().pipe(process.stdout)

In package.json

{
  "name": "my-app",
  "private": true,
  "browserify": {
    "transform": [
      "nanohtml"
    ]
  },
  "dependencies": {
    "nanohtml": "^1.0.0"
  }
}

Bundling

Webpack

At the time of writing there's no Webpack loader yet. We'd love a contribution!

Babel / Parcel

Add nanohtml to your .babelrc config.

Without options:

{
  "plugins": [
    "nanohtml"
  ]
}

With options:

{
  "plugins": [
    ["nanohtml", {
      "useImport": true
    }]
  ]
}

Options

  • useImport - Set to true to use import statements for injected modules. By default, require is used.
  • appendChildModule - Import path to a module that contains an appendChild function. Defaults to "nanohtml/lib/append-child".

Rollup

Use the @rollup/plugin-commonjs plugin with @rollup/plugin-node-resolve. Explicitly import the browser or server entrypoint in your application. E.g.:

import html from 'nanohtml/lib/browser';

Attributions

Shout out to Shama and Shuhei for their contributions to Bel, yo-yoify and pelo. This module is based on their work, and wouldn't have been possible otherwise!

See Also

License

MIT

More Repositories

1

choo

🚂🚋 - sturdy 4kb frontend framework
JavaScript
6,776
star
2

bankai

🚉 - friendly web compiler
JavaScript
1,088
star
3

hyperx

🏷 - tagged template string virtual dom builder
JavaScript
1,010
star
4

nanomorph

🚅 - Hyper fast diffing algorithm for real DOM nodes
JavaScript
726
star
5

nanographql

Tiny graphQL client library
JavaScript
421
star
6

nanocomponent

🚃 - create performant HTML components
JavaScript
366
star
7

wayfarer

👓 composable trie based router
JavaScript
332
star
8

choo-handbook

🚂✋📖 - Learn the choo framework through a set of exercises
HTML
268
star
9

nanobus

🚎 - Tiny message bus
JavaScript
225
star
10

awesome-choo

🌅 Awesome things related with choo framework
197
star
11

create-choo-app

🚞 - create a fresh choo application
JavaScript
181
star
12

nanostate

🚦- Small Finite State Machines
JavaScript
170
star
13

nanorouter

🛤 - Small frontend router
JavaScript
116
star
14

nanocomponent-adapters

🔌 - Convert a nanocomponent to a component for your favourite API or library (web components, (p)react, angular)
JavaScript
96
star
15

choop

🚂⚛️ - choo architecture for preact
JavaScript
93
star
16

on-idle

😴 - Detect when the browser is idle
JavaScript
82
star
17

nanologger

📜 - Cute browser logs
JavaScript
80
star
18

nanoanimation

👨‍🎨 - Safety wrapper around the Web Animation API
JavaScript
72
star
19

nanoraf

🎞 - Only call RAF when needed
JavaScript
71
star
20

choo-devtools

💼 - Expose a choo instance on the window
JavaScript
53
star
21

nanoquery

📇 - Tiny querystring module
JavaScript
49
star
22

nanotask

Microtask queue scheduler for the browser
JavaScript
47
star
23

choo-log

📃 - Development logger for choo
JavaScript
47
star
24

nanoscheduler

Schedule work to be completed when the user agent is idle.
JavaScript
46
star
25

website

🚇 - Hyper Train Transfer Protocol (HTTP)
JavaScript
46
star
26

nanohref

⛓ - Tiny href click handler library
JavaScript
41
star
27

nanotick

process.nextTick() batching utility
JavaScript
37
star
28

choo-store

Lightweight state structure for choo apps.
JavaScript
37
star
29

nanotiming

⏲ - Small timing library
JavaScript
35
star
30

create-choo-electron

:electron: - Create a fresh Choo Electron application
JavaScript
29
star
31

object-change-callsite

Determine the callsite of an object change using Proxies
JavaScript
27
star
32

choo-reload

⛽️ - Livereloading package for choo
JavaScript
27
star
33

on-performance

Listen for performance timeline events
JavaScript
26
star
34

nanobeacon

Small navigator.sendBeacon wrapper
JavaScript
25
star
35

choo-service-worker

👷 - Service worker loader for choo
JavaScript
24
star
36

choo-scaffold

🏗 - Scaffold out files for a Choo project
JavaScript
24
star
37

choo-notification

Web Notification plugin for Choo
JavaScript
22
star
38

nanobounce

Smol debounce package
JavaScript
19
star
39

choo-choo

🎓 learn choo from the command line!
JavaScript
19
star
40

nanomount

Mount a DOM tree on a target node
JavaScript
19
star
41

choo-redirect

🎬 - Redirect a view to another view
JavaScript
19
star
42

persist-storage

🗄 - Enable persistent storage in the browser
JavaScript
19
star
43

nanohistory

Small browser history library
JavaScript
14
star
44

choo-hooks

🎣 - Hook into Choo's events and timings
JavaScript
12
star
45

nanolocation

📍- Small window.location library
JavaScript
10
star
46

discuss

🎭 – Discuss project organization, initiatives, and anything else!
8
star
47

nanocache

Cache Nanocomponents.
JavaScript
7
star
48

bankai-website

JavaScript
6
star
49

choo-umd

🙈 - umd build for choo framework
HTML
3
star