A Custom Elements (v1-spec) code organizer/compiler that tones down Javascript by emphasizing the structure and beauty of HTML.
npm install --save-dev undertone
A custom element definition is nothing more than a self-contained HTML fragment with a custom element tag name that wraps its content, appearance and behavior. Definitions may contain any mix of text, HTML tags, including <script>
, <style>
, <link rel="stylesheet">
and <slot>
tags.
<planet-mars>
<div>${message}</div>
<script>
const message = 'Hello, world'
</script>
</planet-mars>
The compiler rebuilds the above structure representing the source code into a reusable Web component that works on any browser aligned with the ES6+ Custom Elements v1 language specs. The following generated code is an approximate translation:
customElements.define(
'planet-mars',
class extends HTMLElement {
constructor () {
super()
this.attachShadow({ mode: 'open' })
}
connectedCallback () {
const message = 'Hello, world'
let template = document.createElement('template')
template.innerHTML = `<div>${message}</div>`
this.shadowRoot.appendChild(template.content)
}
}
)
Modern and fairly recent mobile and desktop browsers already have native Javascript ES6+ with Custom Elements capability, so polyfills to augment browser capabilities are unnecessary.
See which browsers support these features here:
- Clear separation of form and function (content and behavior)
- Simple format, declarative style: regular HTML5 sprinkled with CSS and Javascript
- Easy to read: IDEs/editors already provide syntax highlighting for HTML
- Generation of source maps to help with debugging
Basic document layout
./index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<x-foo></x-foo>
<script src="js/app.js"></script>
</body>
</html>
Example of a component
./html/x-foo.html
<x-foo>
<script>
console.log('Hello, world')
</script>
</x-foo>
Use the command line tool to compile the component's source code to Javascript and save it to a file.
undertone ./html/x-foo.html -m inline -o ./js/app.js
USAGE: undertone [options] input-file ...
Basic options:
-o, --output output-file Target file (default: stdout)
-m, --map sourcemap-file Generate source map (default: none)
-h, --help Usage information
Advanced options (see documentation):
-c, --class class-file DOM interface (default: undertone.js)
-g, --global Enable global styles (default: scoped styles)
--no-preamble Exclude preamble from output
-o, --output output-file
The name of the generated Javascript file. If omitted, output is sent to stdout
.
-m, --map sourcemap-file
The name of the source map linked to the output file.