Skip to content

Instantly share code, notes, and snippets.

@MorganConrad
Created March 25, 2024 14:27
Show Gist options
  • Save MorganConrad/298cacefe1133fb93fa7549f7a396d0d to your computer and use it in GitHub Desktop.
Save MorganConrad/298cacefe1133fb93fa7549f7a396d0d to your computer and use it in GitHub Desktop.
Utilities for working with Svelte / Vite globs
/* TODO Must be hard-coded, change to fit your project */
const IMPORT_META_GLOB = import.meta.glob("/src/content/*/*.md");
const CONTENT_DIR = "/src/content"; // TPDP move to a config
const = CONTENT_DIR + "/*/*.md";
const INDEX = "/index.md";
export async function filterGlob(regexOrString) {
let regex = (regexOrString instanceof RegExp) ? regexOrString : new RegExp(regexOrString);
let result = {};
Object.entries(IMPORT_META_GLOB).forEach(function([path, resolver]) {
if (regex.test(path))
result[path] = resolver;
})
return result;
}
export async function parseMDGlob(mdGlob, contentDir = CONTENT_DIR) {
const globEntries = Object.entries(mdGlob);
const contentDirLength = contentDir.length;
const markdownFiles = await Promise.all(
globEntries.map(async([urpath, resolver]) => {
const { metadata } = await resolver();
let path = urpath.slice(contentDirLength, -3) // remove contentDir and .md
.replace("/md", ""); // and any internal /md TODO: may beed editing
let fileName = path.split('/').at(-1);
// metadata is readonly, make a modifiable copy,add in path & filename
const meta = Object.assign({}, metadata, { path, fileName });
return {
meta,
path,
fileName
};
})
);
return markdownFiles;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment