Isomorphic <head>
updating and rendering utility.
npm install set-head
import Head from 'set-head'
// Create a new head element, this should be done once per request.
const head = new Head()
// Add elements to head via method chaining.
head
.meta({ charset: 'utf8' })
.title('My App')
.base({ href: '/admin/' })
.meta({ name: 'description' content: 'Cool stuff' })
.link({ rel: 'stylesheet', href: 'index.css' })
.script({ async: true, src: 'index.js' })
set-head
makes overriding default header elements easy. If you invoke head again later it will replace any existing similar element.
The module uses special keying scheme found in ./src/base.js
under const KEYS
to understand which elements to replace and which to add.
// Setting defaults somewhere (perhaps in a middleware or plugin.)
head
.title('My App')
.meta({ name: 'author', content: 'Dylan Piercey' })
.meta({ name: 'description': content: 'Welcome to the site' })
.link({ rel: 'stylesheet', href: 'index.css' })
// The later in a specific route you can continue chaining like so to override.
head
.title('My App > My sub page')
.meta({ name: 'description', content: 'Sub page description' })
// And then if we render we get (formatted for clarity)
head.renderToString() === html`
<title>My App > My sub page</title>
<meta name="author" content="Dylan Piercey">
<meta name="description" content="Sub page description">
<link rel="stylesheet" href="index.css">
`
To render to the browser, simply invoke 'render' after all of the head elements have been set.
head.render()
Server side rendering is accomplished by invoking renderToString
after all of the head elements have been set.
export default (req, res) => {
res.end(`
<!doctype html>
<html>
<head>${head.renderToString()}</head>
<body>
...
</body>
</html>
`)
}
- Use
npm test
to run tests.
Please feel free to create a PR!