Evbogue.com


How to build a basic website with Hyperscript

By Ev Bogue - June 27th 2016

A few days ago I discovered a Node.js module called Hyperscript while I was poking around the code base of a distributed social network that I've been experimenting with.

Hyperscript allows you to write websites inside of JavaScript in an easy-as-possible way. In effect, Hyperscript is an alternative to templating engines because it allows a programmer to avoid templating languages altogether. Instead, a programmer can focus on coding JavaScript to render a website.

In some ways this is similar to Jade, but in others it is different.

At it's most basic level, hyperscript looks similar to this:

var h = require('hyperscript');

h('p',
  'Hello World!'
)

This would output the HTML

<p>Hello World</p>

I also found another Node.js module called hyperscript-helpers that allows you to code with a closer-to-Jade-like syntax

var h = require('hyperscript');

var { h1, p } = require('hyperscript-helpers')(h);

h1('Hello ')

p('world')

Which outputs the following html.

<h1>Hello </h1>
<p>world</p>

As you can see, Hyperscript is a useful tool in JavaScript for generating websites.

I went ahead and created a very basic static website generator using Hyperscript. The code is below.

var h = require('hyperscript'),
    fs = require('fs');
var { html, body, head, title, h1, p } = require('hyperscript-helpers')(h);

var webtitle = 'Hello, ';

var content = 'world.';

var site =
  html(
    head(
      title(webtitle)
    ),
    body(
      h1(webtitle),
      p(content)
    )
  )

fs.writeFile('index.html', site.outerHTML)

Archiving Far Beyond The Stars on the Permanent Web →

← At the event horizon of the Immutable Web

git

This is Decent: ?


about | blog | ssb | decent | ev@evbogue.com | gitmx