Fully-typed utilities for defining, validating and building your document

Overview

zhead

NPM version NPM Downloads GitHub stars

Typed utilities for defining, validating and building best-practice document <head>'s.


Status: Pre-release
Please report any issues 🐛
Made possible by my Sponsor Program 💖
Follow me @harlan_zw 🐦 • Join Discord for help

Features

  • 🇹 Fully typed document <head> with inline doc
  • 💎 Zod powered schema parsing and validation
  • 🔨 Vue bindings for deep reactive Ref and Computed support, useHead compatible
  • 🌳 Composable, tree-shakable and tiny (< 1kb, see export-size-report)

Numerous utilities

  • 🧙 Resolve flat meta tags (100+ typed) unpackMeta
  • SEO inferring to generate minimal tags with maximum SEO buildSeoHead
  • ✍️ Output to HTML generateHtml

Installation

npm install --save-dev zhead

# Using yarn
yarn add --dev zhead

Sub-packages

TypeScript

Typescript base schema for document <head>. Only ships types for easy access to type augmentation.

@zhead/schema

Validation and parsing

Zod schema for validating and parsing head tags.

@zhead/zod

Framework bindings

Vue bindings for handling deep reactive Ref and Computed head tags.

@zhead/vue

API

defineHead

Use this decorator for a simple fully-typed head schema.

import { defineHead } from 'zhead'

const head = defineHead({
  title: 'My Page',
})

// {
//    title: 'My Page',
// }

unpackMeta

Define your meta tags in a simple object with full type-safety.

import { defineHead, resolveMetaFlat } from 'zhead'

const meta = unpackMeta({
  contentSecurityPolicy: {
    contentSrc: 'none'
  },
  viewport: {
    width: 'device-width',
    initialScale: 1,
    userScalable: 'yes',
  }
})

//  [
//    { 'http-equiv': 'content-security-policy', content: 'content-src none' },
//    { 'name': 'viewport', content: 'width=device-width, user-scalable=yes, initial-scale=1' }
//  ]

packMeta

Turn array meta tags into a flat packed object.

import { defineHead, resolveMetaFlat } from 'zhead'

const meta = packMeta([
  {
    'content': 'default-src \'self\' https://example.com; content-src none',
    'http-equiv': 'content-security-policy',
  },
  {
    name: 'description',
    content: 'desc',
  },
  {
    content: '1234567890',
    property: 'fb:app_id',
  },
])

// {
//   "description": "desc",
//   "fbAppId": "1234567890",
//   "contentSecurityPolicy": "default-src 'self' https://example.com; content-src none"
// }

resolveSeoHead

Generate a minimal SEO head with maximum SEO.

Internally this function uses the withDefaults and inferSocialShare utilities.

  • Adds utf-8 charset
  • Sets default best practice viewport
  • Infers social share tags from title and description
  • Sets twitter card to summary_large_image
  • Sets robots best practice
import { resolveSeoHead, resolveMetaFlat } from 'zhead'

const head = resolveSeoHead({
  title: 'Learn about zHead - zHead',
  description: 'Describing the basic usage of zHead.',
})

// {
//   "title": "My Title",
//   "meta": [
//     {
//       "content": "Some description",
//       "name": "description",
//     },
//     {
//       "charset": "utf-8",
//     },
//     {
//       "content": "initial-scale=1, width=device-width",
//       "name": "viewport",
//     },
//     {
//       "content": "My Title",
//       "property": "og:title",
//     },
//     {
//       "content": "Some description",
//       "property": "og:description",
//     },
//     {
//       "content": "max-snippet:-1, max-image-preview:large, max-video-preview:-1",
//       "name": "robots",
//     },
//   ],
// }

Generate API

generateHtml

import { generateHtml } from 'zhead'

const html = generateHtml({
  title: 'test',
  script: [
    { src: 'https://example.com/script.js' },
  ],
  meta: [
    { name: 'description', content: 'test' },
  ]
})

// <title>test</title>
// <meta content="test" name="description">
// <script src="https://example.com/script.js"></script>

generateTags

import { generateTags } from 'zhead'

const tags = generateTags({
  title: 'test',
  script: [
    { src: 'https://example.com/script.js' },
  ],
  meta: [
    { name: 'description', content: 'test' },
  ]
})

// [
//   {
//     "props": {
//       "children": "test",
//     },
//     "tag": "title",
//   },
//   {
//     "props": {
//       "content": "test",
//       "name": "description",
//     },
//     "tag": "meta",
//   },
//   {
//     "props": {
//       "src": "https://example.com/script.js",
//     },
//     "tag": "script",
//   },
// ]

Sponsors

License

MIT License © 2022-PRESENT Harlan Wilton

You might also like...

🌐 Text Input Component for validating and formatting international phone numbers.

🌐  Text Input Component for validating and formatting international phone numbers.

React Native Intl Phone Field Try the Expo Snack 👏 🕹️ Demo It's a javascript-only (no native code) component that can run in iOS, Android, Expo & Re

Jul 8, 2022

An API for producing and validating ActivityPub objects.

ActivityHelper A library that exports an API for producing and validating ActivityPub objects. In a federated system bound together by protocols, it's

May 2, 2022

A JavaScript plugin for entering and validating international telephone numbers

A JavaScript plugin for entering and validating international telephone numbers

International Telephone Input A JavaScript plugin for entering and validating international telephone numbers. It adds a flag dropdown to any input, d

Dec 30, 2022

Little Javascript / Typescript library for validating format of string like email, url, password...

String-Validators Little Javascript / Typescript library for validating format of string like email, url, password... Signaler un Bug · Proposer une F

Oct 14, 2022

io-ts Typed Event Bus for the runtime of your Node.js application. A core for any event-driven architecture based app.

Typed Event Bus Based on io-ts types, this bus provides a handy interface to publish and consume events in the current runtime of the Node.js process.

May 23, 2022

End-to-end typed monorepo template for your next project ⌨️

TYPE ⌨️ TRPC + Yarn Monorepo + Prisma + Expo This template project is a Yarn monorepo with full end-to-end type safety. Powered by: TRPC (on Fastify)

Oct 22, 2022

A zero-dependency, strongly-typed web framework for Bun, Node and Cloudflare workers

nbit A simple, declarative, type-safe way to build web services and REST APIs for Bun, Node and Cloudflare Workers. Examples See some quick examples b

Sep 16, 2022

Demonstration of how you build full-stack, typed, NPM packages, the right way

NPM Packages - The Right way This repository aims to demonstrate how to build NPM packages the right way. my-package should import the shared code, bu

Nov 27, 2022

Typed HyperText Markup Language

Typed HyperText Markup Language You can add types to the HyperText Markup Language. Types To declare two types, they must be separated by a period and

Jan 22, 2022
Comments
  • fix(schema): link `color` attribute

    fix(schema): link `color` attribute

    Description

    The color attribute is used together with the mask-icon rel: https://html.spec.whatwg.org/multipage/semantics.html#attr-link-color

    Linked Issues

    none

    Additional context

    If you agree about this change, would you please add a hacktoberfest-accepted label to this PR? :)

    hacktoberfest-accepted 
    opened by dargmuesli 2
  • fix: 'translate' key missing in HTMLAttributes interface

    fix: 'translate' key missing in HTMLAttributes interface

    Description

    This is important e.g. for Progressive Web Apps (PWAs) where you want to avoid translation suggestions from the browser. The problem occurs in Nuxt 3 app.head.htmlAttrs. Adding the translate key works, but it creates a type error.

    Linked Issues

    Additional context

    opened by toniengelhardt 1
  • Support `application/ld+json` for script tag

    Support `application/ld+json` for script tag

    Clear and concise description of the problem

    For now, script tag type definition only supports text/javascript, module. Could you please add application/ld+json as well? Thank you!

    Suggested solution

    add application/ld+json in script type

    Alternative

    No response

    Additional context

    No response

    Validations

    • [X] Follow our Code of Conduct
    • [X] Read the Contributing Guide.
    • [X] Check that there isn't already an issue that request the same feature to avoid creating a duplicate.
    enhancement 
    opened by rwv 1
Releases(v1.0.9)
Owner
Harlan Wilton
It's not knowing what to do; it's doing what you know.
Harlan Wilton
A jQuery-free general purpose library for building credit card forms, validating inputs and formatting numbers.

A jQuery-free general purpose library for building credit card forms, validating inputs and formatting numbers.

Jesse Pollak 528 Dec 30, 2022
📦 Fully typed and immutable store made on top of Immer with mutation, action, subscription and validation!

Riux is a fully typed and immutable store made on top of Immer with mutation, action, subscription and validation! Table of contents ?? Installation U

null 10 Aug 27, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
A fully-typed, low-level, and HyperScript-like Frontend Library 🚀

A fully-typed, low-level, and HyperScript-like Frontend Library ??

Eliaz Bobadilla 5 Apr 4, 2022
An oversimplification of the TypeScript Compiler API for defining and generating source files.

Tanu ?? A simplified abstraction of the TypeScript Compiler API for defining and generating source files. Tanu ?? Why? What does Tanu mean? ?? How do

Aries 124 Oct 29, 2022
This experimental library patches the global custom elements registry to allow re-defining or reload a custom element.

Redefine Custom Elements This experimental library patches the global custom elements registry to allow re-defining a custom element. Based on the spe

Caridy Patiño 21 Dec 11, 2022
Fast and minimal JS server-side writer and client-side manager.

unihead Fast and minimal JS <head> server-side writer and client-side manager. Nearly every SSR framework out there relies on server-side components t

Jonas Galvez 24 Sep 4, 2022
A simple guide to HTML elements

?? HEAD A simple guide to HTML <head> elements Table of Contents Recommended Minimum Elements Meta Link Icons Social Facebook Open Graph Twitter Card

Josh Buchea 29.5k Jan 1, 2023