I wanted the ability to search my posts on my site, as I often use it to refer to previous posts that I've published. This capability makes the site more of a repository where I can know I can find previous content.
I started with a search on Kagi to see if anyone posted instructions. I immediately found Robb Knights post, Using PageFind with Eleventy for Search. Bingo! I trust Robb's work, so it was a no-brainer.
This approach uses Pagefind static site search library, which works with many static-site generators, including Eleventy.
However, I did have some slight differences, probably because I'm configuring this for the first time on a newer version of Eleventy. I'm running Eleventy 3.0.0 with ESM.
Thanks to Robb's post, and the PageFind documentation that helped me get through this.
Install Pagefind
- I opened Visual Studio Code to my workspace.
- Run the
npm install --save-dev pagefind
.
Tag posts to be indexed
Next, we need to indicate to PageFind, which content we want to index. This is optional.
I opened my _includes/layouts/post.njk
template and in my article
tag, added data-pagefind-body
. Resulting in
Add the Pagefind search box
Next, I added the default Pagefind search UI to my home page.
- Open the
content/index.njk
file. - Above my content, added the following code.
<div id="search" class="search"></div>
<script src="/pagefind/pagefind-ui.js" onload="new PagefindUI({ element: '#search', showImages: false });"></script>
Run Pagefind locally
To test everything locally, run npx -y pagefind --site _site
from the terminal. Change _site to the name of your output directory. This will create the pagefind
directory with your output files.
Run npx @11ty/eleventy --serve to view your site locally. If you added the Pagefind to you home page, it should show the search box.
Run Pagefind Indexing Automatically
To run Pagefind automatically every time I build my site, I opened my package.json file and under scripts, I updated my existing build
to the following : npx @11ty/eleventy && npx -y pagefind --site _site
. This should run the Pagefind index every time the site is built.