nanohtml

repository·master·Indexed 20 days ago

https://github.com/choojs/nanohtml

A lightweight HTML template string library for the browser with built-in support for Server-Side Rendering (SSR) in Node.js. It returns DOM elements in the browser and uses efficient string concatenation in Node. Features include automatic escaping for security, raw HTML interpolation via nanohtml/raw, conditional attribute support, and a Browserify transform for static parsing optimization.

Tokens
3.1K
Snippets
17
Records
18
Agent score
70%

What's inside nanohtml

  1. Handle multiple root elements

    master

    If a nanohtml template string contains multiple top-level elements, they are automatically combined into a single DocumentFragment.

    var html = require('nanohtml')
    
    var el = html`
      <li>Chashu</li>
      <li>Nori</li>
    `
    
    document.querySelector('ul').appendChild(el)
  2. Use nanohtml with Rollup

    master

    To use nanohtml with Rollup, use @rollup/plugin-commonjs and @rollup/plugin-node-resolve. You must explicitly import either the browser or server entrypoint depending on your target environment.

    import html from 'nanohtml/lib/browser';
  3. Optimize nanohtml parsing with Browserify

    master

    You can speed up rendering by parsing HTML statically ahead of time using the nanohtml transform in Browserify. This can be done via CLI, programmatically, or in package.json.

    # 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
    {
      "browserify": {
        "transform": [
          "nanohtml"
        ]
      }
    }
  4. Configure nanohtml with Babel or Parcel

    master

    Babel/Parcel Options

    • useImport: Set to true to use import statements for injected modules. Defaults to require.
    • appendChildModule: Import path to a module that contains an appendChild function. Defaults to "nanohtml/lib/append-child".
    // Without options
    {
      "plugins": [
        "nanohtml"
      ]
    }
    // With options
    {
      "plugins": [
        ["nanohtml", {
          "useImport": true
        }]
      ]
    }
  5. Use yoYoify as a Browserify transform

    master

    yoYoify is a Browserify transform that optimizes nanohtml template strings. It parses your code and converts tagged template literals (using nanohtml, choo/html, or bel) into highly efficient DOM creation code, reducing the overhead of parsing HTML strings at runtime.

    To use it, add it to your Browserify build pipeline. It automatically detects supported view imports and handles transpiled code from Babel or Buble.

    Note: The transform works by replacing template literals with a specialized closure that uses append-child.js and set-attribute.js for performance.

    // Example Browserify usage (conceptual)
    // browserify js/app.js -t yoYoify > bundle.js
  6. Install and use nanohtml

    master

    nanohtml provides a way to create HTML templates using template strings. The package automatically detects its environment and exports either the browser-optimized version or the server-optimized version.

    To use it in a project, install it via npm:

    npm install nanohtml
  7. Use conditional attributes

    master

    To conditionally add HTML attributes, interpolate a JavaScript object into the element tag. If the object is empty, no attributes are added.

    var html = require('nanohtml')
    
    var customAttr = isFuzzy ? { 'data-hand-feel': 'super-fuzzy' } : {}
    var el = html`
      <div ${ customAttr }></div>
    `
  8. Use nanohtml in Node (Server-Side Rendering)

    master

    In Node, where a DOM is not natively available, nanohtml uses efficient string concatenation for rendering. Calling .toString() on the result of a template string will return the HTML string.

    var html = require('nanohtml')
    
    var el = html`
      <body>
        <h1>Hello planet</h1>
      </body>
    `
    
    console.log(el.toString())
  9. Use nanohtml in the Browser

    master

    In a browser environment, nanohtml returns actual DOM elements from template strings. You can then use standard DOM methods like appendChild to add them to the document.

    var html = require('nanohtml')
    
    var el = html`
      <body>
        <h1>Hello planet</h1>
      </body>
    `
    
    document.body.appendChild(el)
  10. Attach event listeners in nanohtml

    master

    You can attach event listeners by using the on[event] attribute syntax within the template string, passing the function name as the interpolated value.

    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`)
    }
  11. Interpolate unescaped HTML with nanohtml/raw

    master

    By default, all content interpolated into nanohtml template strings is escaped for security. To insert raw HTML (for example, output from a markdown renderer), use the nanohtml/raw module.

    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)