Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Hooks to populate the html head.

License

NotificationsYou must be signed in to change notification settings

0no-co/hoofd

Repository files navigation

npm versionBundle size

This project aims at providing a set of hooks to populate<meta>, ... for each page. With crawlers now supportingclient-side alterations it's important to support a fallback model for our<head> tags. The dispatcher located in thislibrary will always make a queue of how we should fallback, ... This way we'll always have some information to give to avisiting crawler.

npm i --save hoofd## ORyarn add hoofd
import{useMeta,useLink,useLang,useTitle,useTitleTemplate}from'hoofd';constApp=()=>{// Will set <html lang="en">useLang('en');// Will set title to "Welcome to hoofd | 💭"useTitleTemplate('%s | 💭');useTitle('Welcome to hoofd');useMeta({name:'author',content:'Jovi De Croock'});useLink({rel:'me',href:'https://jovidecroock.com'});return<p>hoofd</p>;};

Or you can choose to

import{useHead,useLink}from'hoofd';constApp=()=>{useHead({title:'Welcome to hoofd | 💭',language:'en',metas:[{name:'author',content:'Jovi De Croock'}],});useLink({rel:'me',href:'https://jovidecroock.com'});return<p>hoofd</p>;};

Preact

If you need support forPreact you can import fromhoofd/preact instead.

Gatsby

There's a plugin that hooks in withGatsby and thatwill fill in themeta, ... in your build process.

Hooks

This package exportsuseTitle,useTitleTemplate,useMeta,useLink anduseLang. These hooksare used to control information conveyed by the<head> in an html document.

useTitle

This hook accepts a string that will be used to set thedocument.title, every time thegiven string changes it will update the property.

useTitleTemplate

This hook accepts a string, which will be used to format the result ofuseTitle wheneverit updates. Similar to react-helmet, the placeholder%s will be replaced with thetitle.

useMeta

This hook accepts the regular<meta> properties, beingname,property,httpEquiv,charset andcontent.

These have to be passed as an object and will update whencontent changes.

useLink

This hook accepts the regular<link> properties, beingrel,as,media,href,sizes andcrossorigin.

This will update within the sameuseLink but will never go outside

useLang

This hook accepts a string that will be used to set thelang property on thebase<html> tag. Every time this string gets updated this will be reflected in the dom.

useScript

This hook accepts a few arguments and will lead to an injection of a script tag into the dispatcher (during ssr)or the DOM (during csr).

  • src?: this can be a location where the script lives, for examplepublic/x.js or an inline script for exampledata:application/javascript,alert("yolo").
  • id?: a unique identifier used for querying the script tag. Atleast one amongsrc andid prop is mandatory.
  • text?: this sets the innertext on the script tag. Can be used for addingembedded data,rich text data.
  • type?: this sets thetype attribute on the script tag.
  • async?: this sets theasync attribute on the script tag.
  • defer?: this sets thedefer attribute on the script tag.
  • module?: this property will override thetype atrribute on the script tag with a value ofmodule.
  • crossorigin?: 'anonymous' | 'use-credentials';
  • integrity?: string;

SSR

We expose a method calledtoStatic that will return the following properties:

  • title, the currenttitle dictated by the deepestuseTitleTemplate anduseTitle combination
  • lang, the currentlang dictated by the deepestuseLang
  • metas, an array of unique metas bykeyword (property, ...)
  • links, the links aggregated from the render pass.

The reason we pass these as properties is to better supportgatsby, ...

If you need to stringify these you can use the following algo:

conststringify=(title,metas,links)=>{conststringifyTag=(tagName,tags)=>tags.reduce((acc,tag)=>`${acc}<${tagName}${Object.keys(tag).reduce((properties,key)=>`${properties}${key}="${tag[key]}"`,'')}>`,'');return`    <title>${title}</title>${stringifyTag('meta',metas)}${stringifyTag('link',links)}  `;};
import{toStatic}from'hoofd';constreactStuff=renderToString();const{ metas, links, title, lang}=toStatic();conststringified=stringify(title,metas,links);consthtml=`  <!doctype html>    <html${lang ?`lang="${lang}"` :''}>      <head>${stringified}      </head>      <body>        <div>${reactStuff}        </div>      </body>  </html>`;

Context API

By default this package relies on a statically-initialized context provider to accumulate anddispatch<head> and<meta> changes. In cases where you may want to control the Dispatcherinstance used, this module exports aHoofdProvider context provider andcreateDispatcherfunction for creating valid context instances.

import{createDispatcher,HoofdProvider}from'hoofd';functionssr(App){constdispatcher=createDispatcher();constwrappedApp=(<HoofdProvidervalue={dispatcher}><App/></HoofdProvider>);constmarkup=renderToString(wrappedApp);const{ metas, links, title, lang}=dispatcher.toStatic();// See example above for potential method to consume these static results.}

[8]ページ先頭

©2009-2025 Movatter.jp