kentcdodds / mdx-bundler

🦤 Give me MDX/TSX strings and I'll give you back a component you can render. Supports imports!
MIT License
1.78k stars 75 forks source link

Generated code contains also frontmatters #210

Closed nullndr closed 1 year ago

nullndr commented 1 year ago

Relevant code or config

// posts.server.ts

import { remarkCodeHike } from "@code-hike/mdx";
import { readFile } from "fs/promises";
import { bundleMDX } from "mdx-bundler";
import codeHikeTheme from "shiki/themes/one-dark-pro.json";

type FrontMatter = {
  title: string;
  description: string;
  publishedAt: string;
};

export const getMdxFile = async (file: string) => {
  return bundleMDX<FrontMatter>({
    source: (await readFile(`./posts/${file}.mdx`)).toString(),
    mdxOptions() {
      return {
        remarkPlugins: [
          [
            remarkCodeHike,
            {
              theme: codeHikeTheme,
              lineNumbers: true,
              showCopyButton: true,
              autoImport: true,
            },
          ],
        ],
      };
    },
  });
};

// app/routes/post.$name.tsx

import React from "react";
import { Title } from "~/components/Title";
import { getMdxFile } from "~/utils/posts.server";

export const loader = async ({ params }: LoaderArgs) => {
  const name = params.name;
  if (name == null) {
    throw new Response(null, { status: 400 });
  }

  return getMdxFile(name);
};

export default function () {
  const {
    code,
    frontmatter: { title },
  } = useLoaderData<typeof loader>();
  const MdxComponent = React.useMemo(() => getMDXComponent(code), [code]);

  return (
    <>
      <Title>{title}</Title>
      <div className="m-3 mt-10 xl:w-1/2 prose dark:prose-invert prose-a:no-underline prose-a:font-bold">
        <MdxComponent />
      </div>
    </>
  );
}
// baz.mdx

---
title: baz
publishedAt: 2023-02-13
description: Lorem ipsum dolor sit amet
---

Lorem ipsum dolor sit amet, consectetur ...

What happened:

image

Problem description:

As you can see the generated html code contains also the data from the frontmatter, but from the README.md file it shouldn't be here.

Am I missing something?

nullndr commented 1 year ago

I forgot to add options.remarkPlugins on bundleMDX.mdxOptions, sorry!