JWen's Blog

Personal website of JWen 丁文亮的个人网站

Add Search to Hugo with Pagefind

2024-09-23


References

  1. Install pagefind via npx (or download a precompiled release from GitHub)

    Note that specialized languages are only supported in Pagefind’s extended release, which is the default when running npx pagefind. (Ref)

  2. In the Hugo site directory (for me, ~/Desktop/blog)

    hugo
    npx pagefind --site "public"
    hugo server -N -F
    
  3. Add a search page. E.g. write a content/search.md file as follows

    +++
    title = "Search"
    draft = false
    slug = "search"
    +++
    
    <link href="/pagefind/pagefind-ui.css" rel="stylesheet">
    <link href="/css/pagefind.css" rel="stylesheet">
    <script src="/pagefind/pagefind-ui.js"></script>
    <div id="search"></div>
    <script>
        window.addEventListener('DOMContentLoaded', (event) => {
            new PagefindUI({ element: "#search", showSubResults: true });
        });
    </script>
    
  4. Customize the style of Pagefind UI (Ref). I already add

    <link href="/css/pagefind.css" rel="stylesheet">
    

    to content/search.md, what remains is to store the script in static/css/pagefind.css and tweak it to fit your theme.

    body {
        --pagefind-ui-scale: .8;
        --pagefind-ui-primary: rgb(30,144,255);
        --pagefind-ui-text: rgb(240,248,255);
        --pagefind-ui-background: #181B20;
        --pagefind-ui-border: rgb(240,248,255);
        --pagefind-ui-tag: rgb(30,144,255);
        --pagefind-ui-border-width: 1px;
        --pagefind-ui-border-radius: 5px;
        --pagefind-ui-image-border-radius: 8px;
        --pagefind-ui-image-box-ratio: 3 / 2;
        --pagefind-ui-font: sans-serif;
    }
    
  5. Open a browser with the address http://localhost:1313/search/ and try Search!

  6. For a better experience of Chinese searching, we can use the Force Language Flag (see also Ref1 and Ref2) in Step 2

    npx pagefind --site "public" --force-language "zh"
    

    If we have downloaded the precompiled release of pagefind_extended and added/linked it to the PATH, the following is faster

    pagefind_extended --site "public" --force-language "zh"