Hyperscript-Adapter
This library is a utility for writing HTML in JavaScript in a short syntax. It supports web frameworks that define a h
or a createElement
function, such as React.
Install
Simpily run:
npm install --save hyperscript-adapter
Loading
Once this library is installed, load the file using a script or requirejs.
Script loading:
Requirejs loading:
;
If requirejs is loaded before the HTML script, then HTML is exported:
;
Settings
Important: Do not override these settings unless you define a custom h
.
hyphenate: // Which properties to convert from camelCase to kebab-case. style: true // Includes 'custom-vars-only' to only escape __fooBar as --foo-bar. classes: true // Hyphenate classes. See hyphenate ids below. tag: true // Hyphenate tags. In most cases this should be true for compatibility with web components. id: true // Hyphenate ids: HTML._$fooBar() would be equal to HTML["_$foo-bar"]() data: true // Hyphenate dataFoo to data-foo. {} // First argument is the input, second is the toKebabCase function. This allows for custom middleware that gets executed before the call to h. document // The function that is called when an element is text. combineId: false // Whether to call h with the id being combined (tag#foo) combineClasses: false // Whether to call h with the classes being combined (tag.foo.bar) fixArrays: true // Whether to flatten the second argument: HTML._({}, [elem, otherelem]) would be equivalent as HTML._({}, elem, otherelem) { // This is the function called at the end. const element = document; for const k v of Object if k === 'style' const style = elementstyle; if typeof v === 'string' stylecssText = v; else for const sk sv of Object style; else if k element; else elementk = v; elements; // This property is adjusted. return element; } resolvers: // Functions that resolve names such as the tag name. // The second argument is the toKebabCase function, and the third is the entire settings passed in. opthyphenatetag ? : tag opthyphenateid ? : id opthyphenateclasses ? : cl
Usage
It is highly suggested to alias HTML to a shorter variable such as h
. This is not provided by default as in browsers it may override the normal hyperscript that would be passed into settings.
// Creates a div.HTML// Creates a div, with id "foo-bar".HTML// Creates a div, with classes "foo-bar" and "qux".HTMLdivfooBar// Both at once.HTMLdiv$fooBar// Div shorthandHTML// Default tag is div: This outputs a div with id "foo-bar" and classes "qux"HTML$fooBar// Some settings.HTML// Data properties and custom css variables.HTML// ChildrenHTML// Children (in array). This is exactly identical to the previous one.HTML// Custom settings.const BetterHTML = ;
The full usage can be seen in tests.js
.