Unverified Commit 93323704 authored by Jam Balaya's avatar Jam Balaya Committed by GitHub

examples: update `with-mdx-remote` example to utilize the App Router (#74067)

## Description

This PR updates the
[`with-mdx-remote`](https://github.com/vercel/next.js/tree/canary/examples/with-mdx-remote)
example to use the App Router and TypeScript. Here are the changes that
have been made:

1. Renamed the `pages` folder to the `app` folder.
2. Converted JavaScript to TypeScript files and created `tsconfig.json`.
3. Created a new `global.css` and `layout.tsx` files in the app
directory.
4. Used [CSS module](https://github.com/css-modules/css-modules) instead
of [styled-jsx](https://github.com/vercel/styled-jsx).
5. Removed
[`next-remote-watch`](https://github.com/hashicorp/next-remote-watch)
due to incompatibility and no maintenance.
6. Removed [`gray-matter`](https://github.com/jonschlinkert/gray-matter)
and implement front-matter parser as well.
7. Updated the `.gitignore`, `package.json` and README.md files.

The new app looks and works much the same as the old one.

### Adding or Updating Examples

- [x] The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- [x] Make sure the linting passes by running `pnpm build && pnpm lint`.
See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

---------
Co-authored-by: 's avatarSam Ko <sam@vercel.com>
parent d31b8b82
......@@ -28,9 +28,10 @@
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# local env files
.env*.local
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
......
# MDX Remote Example
This example shows how a simple blog might be built using the [next-mdx-remote](https://github.com/hashicorp/next-mdx-remote) library, which allows mdx content to be loaded via `getStaticProps` or `getServerSideProps`. The mdx content is loaded from a local folder, but it could be loaded from a database or anywhere else.
The example also showcases [next-remote-watch](https://github.com/hashicorp/next-remote-watch), a library that allows next.js to watch files outside the `pages` folder that are not explicitly imported, which enables the mdx content here to trigger a live reload on change.
Since `next-remote-watch` uses undocumented Next.js APIs, it doesn't replace the default `dev` script for this example. To use it, run `npm run dev:watch` or `yarn dev:watch`.
This example shows how a simple blog might be built using the [next-mdx-remote](https://github.com/hashicorp/next-mdx-remote) library, which allows mdx content to be loaded via [`generateStaticParams`](https://nextjs.org/docs/app/api-reference/functions/generate-static-params). The mdx content is loaded from a local folder, but it could be loaded from a database or anywhere else.
## Deploy your own
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example) or preview live with [StackBlitz](https://stackblitz.com/github/vercel/next.js/tree/canary/examples/with-mdx-remote)
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-mdx-remote&project-name=with-mdx-remote&repository-name=with-mdx-remote)
## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example:
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), [pnpm](https://pnpm.io), or [Bun](https://bun.sh/docs/cli/bunx) to bootstrap the example:
```bash
npx create-next-app --example with-mdx-remote with-mdx-remote-app
......@@ -28,56 +24,39 @@ yarn create next-app --example with-mdx-remote with-mdx-remote-app
pnpm create next-app --example with-mdx-remote with-mdx-remote-app
```
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
```bash
bunx create-next-app --example with-mdx-remote with-mdx-remote-app
```
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/app/building-your-application/deploying)).
## Notes
### Conditional custom components
When using `next-mdx-remote`, you can pass custom components to the MDX renderer. However, some pages/MDX files might use components that are used infrequently, or only on a single page. To avoid loading those components on every MDX page, you can use `next/dynamic` to conditionally load them.
When using `next-mdx-remote`, you can pass custom components to the MDX renderer. However, some pages/MDX files might use components that are used infrequently, or only on a single page. To avoid loading those components on every MDX page, you can use [`next/dynamic`](https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading#nextdynamic) to conditionally load them.
For example, here's how you can change `getStaticProps` to pass a list of component names, checking the names in the page render function to see which components need to be dynamically loaded.
```js
```typescript
import dynamic from "next/dynamic";
import Test from "../components/test";
import Test from "@/components/test";
import { MDXRemote, type MDXRemoteProps } from 'next-mdx-remote/rsc'
const SomeHeavyComponent = dynamic(() => import("SomeHeavyComponent"));
const SomeHeavyComponent = dynamic(() => import("../component/SomeHeavyComponent"));
const defaultComponents = { Test };
export function SomePage({ mdxSource, componentNames }) {
export function CustomMDX(props: MDXRemoteProps) {
const componentNames = [
/<SomeHeavyComponent/.test(props.source as string) ? "SomeHeavyComponent" : "",
].filter(Boolean);
const components = {
...defaultComponents,
SomeHeavyComponent: componentNames.includes("SomeHeavyComponent")
? SomeHeavyComponent
: null,
: () => null,
};
return <MDXRemote {...mdxSource} components={components} />;
}
export async function getStaticProps() {
const source = `---
title: Conditional custom components
---
Some **mdx** text, with a default component <Test name={title}/> and a Heavy component <SomeHeavyComponent />
`;
const { content, data } = matter(source);
const componentNames = [
/<SomeHeavyComponent/.test(content) ? "SomeHeavyComponent" : null,
].filter(Boolean);
const mdxSource = await serialize(content);
return {
props: {
mdxSource,
componentNames,
},
};
return <MDXRemote {...props} components={components} />;
}
```
import { notFound } from "next/navigation";
import { CustomMDX } from "@/components/mdx";
import { getPosts } from "@/lib/utils";
import styles from "./page.module.css";
import Link from "next/link";
export function generateStaticParams() {
const posts = getPosts();
return posts.map((post) => ({
slug: post.slug,
}));
}
export default async function Blog({
params,
}: {
params: Promise<{ slug: string }>;
}) {
const slug = (await params).slug;
const post = getPosts().find((post) => post.slug === slug);
if (!post) {
notFound();
}
return (
<>
<header>
<nav>
<Link href="/">👈 Go back home</Link>
</nav>
</header>
<main>
<h1 className={styles.postHeader}>{post.metadata.title}</h1>
{post.metadata.description && (
<p className={styles.description}>{post.metadata.description}</p>
)}
<article>
<CustomMDX source={post.content} />
</article>
</main>
</>
);
}
:root {
--background: #ffffff;
--foreground: #171717;
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
html,
body {
font: 100%/1.5 system-ui;
max-width: 100vw;
overflow-x: hidden;
}
body {
color: var(--foreground);
background: var(--background);
font-family: Arial, Helvetica, sans-serif;
max-width: 36rem;
margin: 0 auto;
padding: 1.5rem;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
a {
color: inherit;
text-decoration-thickness: 2px;
}
a:hover {
color: royalblue;
text-decoration-color: currentcolor;
}
p {
margin-bottom: 1.5rem;
}
code {
font-family: Menlo;
}
@media (prefers-color-scheme: dark) {
html {
color-scheme: dark;
}
}
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "MDX Remote App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={`${geistSans.variable} ${geistMono.variable}`}>
{children}
</body>
</html>
);
}
import Link from "next/link";
import { getPosts } from "@/lib/utils";
export default function Home() {
const posts = getPosts();
return (
<main>
<h1>Home Page</h1>
<p>
Click the link below to navigate to a page generated by{" "}
<code>next-mdx-remote</code>.
</p>
<ul>
{posts.map((post) => (
<li key={post.slug}>
<Link href={`/${post.slug}`}>{post.metadata.title}</Link>
</li>
))}
</ul>
</main>
);
}
---
title: Example Post
description: This frontmatter description will appear below the title
---
This is an example post, with with a [link](https://nextjs.org) and a React component:
<Greet name="next-mdx-remote" />
Links are rendered using a custom component passed to `next-mdx-remote`.
Go back [home](/).
---
title: Hello World
---
This is an example post. There's another one [here](/example-post).
import Link from "next/link";
export default function CustomLink({ as, href, ...otherProps }) {
return (
<>
<Link as={as} href={href} legacyBehavior>
<a {...otherProps} />
</Link>
<style jsx>{`
a {
color: tomato;
}
`}</style>
</>
);
}
export default function Layout({ children }) {
return (
<>
<div className="wrapper">{children}</div>
<style jsx>{`
.wrapper {
max-width: 36rem;
margin: 0 auto;
padding: 1.5rem;
}
`}</style>
<style jsx global>{`
* {
margin: 0;
padding: 0;
}
:root {
--site-color: royalblue;
--divider-color: rgba(0, 0, 0, 0.4);
}
html {
font: 100%/1.5 system-ui;
}
a {
color: inherit;
text-decoration-color: var(--divider-color);
text-decoration-thickness: 2px;
}
a:hover {
color: var(--site-color);
text-decoration-color: currentcolor;
}
h1,
p {
margin-bottom: 1.5rem;
}
code {
font-family: "Menlo";
}
`}</style>
</>
);
}
export default function TestComponent({ name = "world" }) {
return (
<>
<div>Hello, {name}!</div>
<style jsx>{`
div {
background-color: #111;
border-radius: 0.5em;
color: #fff;
margin-bottom: 1.5em;
padding: 0.5em 0.75em;
}
`}</style>
</>
);
}
.div {
background-color: #111;
border-radius: 0.5em;
color: #fff;
margin-bottom: 1.5em;
padding: 0.5em 0.75em;
}
import styles from "./greet.module.css";
export function Greet({ name = "world" }: { name: string }) {
return <div className={styles.div}>Hello, {name}!</div>;
}
.a {
color: tomato;
text-decoration-color: rgba(0, 0, 0, 0.4);
}
import React from "react";
import Link from "next/link";
import { MDXRemote, type MDXRemoteProps } from "next-mdx-remote/rsc";
import { Greet } from "./greet";
import styles from "./mdx.module.css";
function CustomLink({
href,
children,
...props
}: React.LinkHTMLAttributes<HTMLAnchorElement>) {
if (href?.startsWith("/")) {
return (
<Link href={href} className={styles.a} {...props}>
{children}
</Link>
);
}
if (href?.startsWith("#")) {
return (
<a href={href} className={styles.a} {...props}>
{children}
</a>
);
}
return (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className={styles.a}
{...props}
>
{children}
</a>
);
}
export function CustomMDX(props: MDXRemoteProps) {
const components = {
a: CustomLink,
Greet: Greet,
};
return (
<MDXRemote
{...props}
components={{ ...components, ...(props.components || {}) }}
/>
);
}
import fs from "node:fs";
import path from "node:path";
type Metadata = {
title: string;
description?: string;
};
function parseFrontmatter(fileContent: string) {
const frontmatterRegex = /---\s*([\s\S]*?)\s*---/;
const content = fileContent.replace(frontmatterRegex, "").trim();
const match = frontmatterRegex.exec(fileContent);
const frontMatterBlock = match![1];
const frontMatterLines = frontMatterBlock.trim().split("\n");
const metadata: Partial<Metadata> = {};
frontMatterLines.forEach((line) => {
const [key, ...valueArr] = line.split(": ");
let value = valueArr.join(": ").trim();
value = value.replace(/^['"](.*)['"]$/, "$1"); // Remove quotes
metadata[key.trim() as keyof Metadata] = value;
});
return { metadata: metadata as Metadata, content: content };
}
function getMDXFiles(dir: fs.PathLike) {
return fs.readdirSync(dir).filter((file) => path.extname(file) === ".mdx");
}
function readMDXFile(filePath: fs.PathOrFileDescriptor) {
const rawContent = fs.readFileSync(filePath, "utf-8");
return parseFrontmatter(rawContent);
}
function getMDXData(dir: fs.PathLike) {
const mdxFiles = getMDXFiles(dir);
return mdxFiles.map((file) => {
const { metadata, content } = readMDXFile(path.join(dir.toString(), file));
const slug = path.basename(file, path.extname(file));
return {
metadata,
slug,
content,
};
});
}
export function getPosts() {
return getMDXData(path.join(process.cwd(), "app", "posts"));
}
{
"private": true,
"scripts": {
"dev": "next",
"dev:watch": "next-remote-watch ./posts",
"dev": "next dev --turbopack",
"build": "next build",
"start": "next start"
},
"dependencies": {
"gray-matter": "^4.0.2",
"next": "latest",
"next-mdx-remote": "^3.0.1",
"next-remote-watch": "1.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
"next-mdx-remote": "^5.0.0",
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@types/node": "^22.10.2",
"@types/react": "^19.0.2",
"@types/react-dom": "^19.0.2",
"typescript": "^5.7.2"
}
}
import fs from "fs";
import matter from "gray-matter";
import Link from "next/link";
import path from "path";
import Layout from "../components/Layout";
import { postFilePaths, POSTS_PATH } from "../utils/mdxUtils";
export default function Index({ posts }) {
return (
<Layout>
<h1>Home Page</h1>
<p>
Click the link below to navigate to a page generated by{" "}
<code>next-mdx-remote</code>.
</p>
<ul>
{posts.map((post) => (
<li key={post.filePath}>
<Link
as={`/posts/${post.filePath.replace(/\.mdx?$/, "")}`}
href={`/posts/[slug]`}
>
{post.data.title}
</Link>
</li>
))}
</ul>
</Layout>
);
}
export function getStaticProps() {
const posts = postFilePaths.map((filePath) => {
const source = fs.readFileSync(path.join(POSTS_PATH, filePath));
const { content, data } = matter(source);
return {
content,
data,
filePath,
};
});
return { props: { posts } };
}
import fs from "fs";
import matter from "gray-matter";
import { MDXRemote } from "next-mdx-remote";
import { serialize } from "next-mdx-remote/serialize";
import dynamic from "next/dynamic";
import Head from "next/head";
import Link from "next/link";
import path from "path";
import CustomLink from "../../components/CustomLink";
import Layout from "../../components/Layout";
import { postFilePaths, POSTS_PATH } from "../../utils/mdxUtils";
// Custom components/renderers to pass to MDX.
// Since the MDX files aren't loaded by webpack, they have no knowledge of how
// to handle import statements. Instead, you must include components in scope
// here.
const components = {
a: CustomLink,
// It also works with dynamically-imported components, which is especially
// useful for conditionally loading components for certain routes.
// See the notes in README.md for more details.
TestComponent: dynamic(() => import("../../components/TestComponent")),
Head,
};
export default function PostPage({ source, frontMatter }) {
return (
<Layout>
<header>
<nav>
<Link href="/" legacyBehavior>
<a>👈 Go back home</a>
</Link>
</nav>
</header>
<div className="post-header">
<h1>{frontMatter.title}</h1>
{frontMatter.description && (
<p className="description">{frontMatter.description}</p>
)}
</div>
<main>
<MDXRemote {...source} components={components} />
</main>
<style jsx>{`
.post-header h1 {
margin-bottom: 0;
}
.post-header {
margin-bottom: 2rem;
}
.description {
opacity: 0.6;
}
`}</style>
</Layout>
);
}
export const getStaticProps = async ({ params }) => {
const postFilePath = path.join(POSTS_PATH, `${params.slug}.mdx`);
const source = fs.readFileSync(postFilePath);
const { content, data } = matter(source);
const mdxSource = await serialize(content, {
// Optionally pass remark/rehype plugins
mdxOptions: {
remarkPlugins: [],
rehypePlugins: [],
},
scope: data,
});
return {
props: {
source: mdxSource,
frontMatter: data,
},
};
};
export const getStaticPaths = async () => {
const paths = postFilePaths
// Remove file extensions for page paths
.map((path) => path.replace(/\.mdx?$/, ""))
// Map the path into the static paths object required by Next.js
.map((slug) => ({ params: { slug } }));
return {
paths,
fallback: false,
};
};
---
title: Example Post
description: This frontmatter description will appear below the title
---
This is an example post, with a [link](https://nextjs.org) and a React component:
<TestComponent name="next-mdx-remote" />
The title and description are pulled from the MDX file and processed using `gray-matter`. Additionally, links are rendered using a custom component passed to `next-mdx-remote`.
Go back [home](/).
---
title: Hello World
---
This is an example post. There's another one [here](/posts/example-post).
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
import fs from "fs";
import path from "path";
// POSTS_PATH is useful when you want to get the path to a specific file
export const POSTS_PATH = path.join(process.cwd(), "posts");
// postFilePaths is the list of all mdx files inside the POSTS_PATH directory
export const postFilePaths = fs
.readdirSync(POSTS_PATH)
// Only include md(x) files
.filter((path) => /\.mdx?$/.test(path));
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment