markdown-posts
TypeScript icon, indicating that this package has built-in type declarations

0.1.1 • Public • Published

Markdown Posts

A simple API to transform a directory of markdown files with frontmatter into data.

Usage

Installation

Install the package:

npm install markdown-posts

Usage

By default, markdown-posts looks for all markdown files in the posts directory.

Below is a basic example in Next.js:

List all posts on home page:

pages/index.tsx

import { getAllPosts } from "markdown-posts";

export default function Home({ posts }) {
  return (
    <ul>
      {posts.map((post, index) => (
        <li>{post.title}</li>
      ))}
    </ul>
  );
}

export async function getStaticProps() {
  const posts = await getAllPosts(["title", "date", "slug"]);

  return {
    props: {
      posts,
    },
  };
}

Display a single post:

pages/[slug].tsx

import { getPostBySlug, getAllPosts } from "markdown-posts";

export default function SinglePost({ post }) {
  return (
    <article>
      <h1>{post.title}</h1>

      <div dangerouslySetInnerHTML={{ __html: post.content }} />
    </article>
  );
}

export async function getStaticProps({ params }) {
  const { slug } = params;
  const post = await getPostBySlug(slug, ["title", "date", "slug"]);

  return {
    props: {
      post,
    },
  };
}

export async function getStaticPaths() {
  const posts = await getAllPosts(["slug"]);

  return {
    paths: posts.map((post) => {
      return {
        params: {
          slug: post.slug,
        },
      };
    }),
    fallback: false,
  };
}

License

This project is licensed under the MIT license

Package Sidebar

Install

npm i markdown-posts

Weekly Downloads

0

Version

0.1.1

License

MIT

Unpacked Size

15.4 kB

Total Files

10

Last publish

Collaborators

  • blakewilson