Blog Contents Optimized with Astro.glob
Using Astro.glob
When I set up this site, I didn't use the "blog" option in the Astro CLI
wizard. The "blog" of this site is intended to be a secondary artifact,
documenting the build process for those curious and for my own record of
chronology. The main focus will be the resumé, portfolio, and other content
pages. This left me unaware of how a default Astro "blog" is coded. So I
generated the table of contents for the blog by my own invention using
readdir, readFile
from node:fs
. I was surprised to
see an IDE warning. After looking through the docs, I found that native
packages are discouraged and should use the
Astro.glob method
instead. After this update, the code footprint was reduced > 80%! ✨
import { orderBy } from 'lodash';
const posts = await Astro.glob('./*.md'); // Top-level await 🤘
const ordered = orderBy(posts, 'frontmatter.date', 'desc');
Adding .astro pages
Another thing that was bothering me about the blog was I couldn't add components
to blog posts since I set up the pages and layout for use with markdown documents
(*.md
). To demonstrate components directly in blog posts, I either had to add the
MDX integration
or add support for Astro pages.
I spent a little bit of time on the MDX integration and decided that adding Astro pages was simpler. The main laziness factor for me was being able to spoof frontmatter metadata in pages. Declaring frontmatter in MDX didn't work the same as MD files and it seemed declaring frontmatter at all required some extra packages to install and figure out.
With pages, I found that exported values are available in
the returned collection from Astro.glob
so spoofing
frontmatter
in a page is straightforward and meets my criteria
for laziness:
export const frontmatter = {
title: 'Blog Contents Optimized',
author: 'Brad Barwick',
date: '2022-09-02 Fri',
};
Now that uniform frontmatter
is available for both Astro pages and markdown files,
I simply increase the scope of my Astro.glob
wildcard and it works!
const posts = await Astro.glob('./*');
const ordered = orderBy(posts, 'frontmatter.date', 'desc');