next-pagefind

Use Pagefind with any live server.

Insallation

Install the modules required for the program.

  1. cargo install spider_cli
  2. cargo install pagefind
  3. cargo install next-pagefind

Getting Started

  1. Start the dev or prod instance on port 3000 and run next-pagefind at the root directory of your next application to create your search index's and output the content into the public folder.

  2. Optional: Add data-pagefind-meta="url[href]" on your meta hrefLang links example: <link rel="alternate" hrefLang="en" href="https://a11ywatch.com/blog/version-your-proto-definitions-for-stablity" data-pagefind-meta="url[href]"/> to replace the location of the links.

  3. Setup pagefind in the your next.js project. The example before uses the layout to setup the PageFindUI wasm module once.

```tsx // pagefind.tsx import { useEffect, useRef } from 'react'

export const PageFind = () => { const loaded = useRef(false)

useEffect(() => { if (!loaded.current) { loaded.current = true let observer: MutationObserver

  const PagefindUI =
    // @ts-ignore
    typeof window.PagefindUI !== 'undefined' && window.PagefindUI

  if (PagefindUI) {
    try {
      new PagefindUI({
        element: '#search',
        resetStyles: false,
        showImages: false,
        showEmptyFilters: false,
      })

      // delete the observer code below if you did step 2 and target production websites
      const pagefindDrawer = document.querySelector('.pagefind-ui__drawer')

      // replace the .html from links with path
      if (pagefindDrawer) {
        const callback = () => {
          const links: NodeListOf<HTMLAnchorElement> =
            document.querySelectorAll('.pagefind-ui__result-link')

          for (const link of links) {
            link.href = link.href.replace('.html', '')
          }
        }

        observer = new MutationObserver(callback)

        observer.observe(pagefindDrawer, {
          attributes: false,
          childList: true,
          subtree: true,
        })
      }
    } catch (e) {
      console.error(e)
    }
  }

  return () => {
    if (observer) {
      observer.disconnect()
    }
  }
}

}, [loaded])

return (

) } ```

```tsx // layout.tsx import React from 'react'

// use layout for scripts _pagefind export function Layout({ children }) { return ( <>