How would you get a list of posts including metadata? #220
-
I want to get a list of all posts in my import allPosts from './posts/*.md' In short: when I create a new Essentially, I want /posts
first-post.md
second-post.md to turn into something like this on the front-end My Blog
1. First Post
2. Second Post |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 4 replies
-
I'm currently using import-all.macro simply because the alternatives I've found are not as actively maintained but have also used babel-plugin-import-glob-array. Something like the snippet below would work. import importAll from 'import-all.macro'
export const posts = Object.entries(importAll.sync('./posts/*.svx')) |
Beta Was this translation helpful? Give feedback.
-
This is easier in SvelteKit, because you can use Vite's globImport. Here's how I did it: <script>
import globToArray from '$lib/globToArray'
const modules = import.meta.globEager('./blog/*.svx')
const posts = globToArray(modules)
</script>
I found it worked better with To access the component itself, you can use {#each posts as post}
<svelte:component this={post.default} />
{/each} |
Beta Was this translation helpful? Give feedback.
-
SvelteKit approach to fetch the posts data: const glob_import = import.meta.glob<{ default: SvelteComponent; metadata: Record<string, any> }>(
'./writing/*.md',
{
eager: true
}
);
const writings = Object.entries(glob_import);
console.log({ writings }); This will return the posts data like this: type Path = string; // The file path
type Module = {
default: SvelteComponent; // The Svelte Component
metadata: Record<string, any> // An object containing the frontmatter
}
type Writings = [Path, Module][]; // Writings
[
[
"./writing/test.md",
{
default: SvelteComponent,
metadata: {
layout: "writing",
title: "Post One",
subtitle: "Test",
author: "alex",
date: "August 9th, 2022"
}
}
]
] If you want to mount the components, you can do it like: {#each writings as [path, module]}
<svelte:component this={module.default} />
{/each} |
Beta Was this translation helpful? Give feedback.
SvelteKit approach to fetch the posts data:
This will return the posts data like this: