How to Use Markdown with Astro: Simple Guide
In Astro, you can use markdown by importing
.md or .mdx files directly as components. Astro supports rendering markdown content with frontmatter and lets you combine markdown with Astro components for flexible page building.Syntax
Astro lets you import markdown files as components using the import statement. You can write frontmatter at the top of your markdown file using --- to define metadata. Then, you use the markdown content as JSX inside your Astro page.
Example parts:
import Post from './post.md'imports the markdown file as a component.---marks frontmatter start and end in markdown.- You use
<Post />in your Astro file to render the markdown content.
markdown
--- title: "My First Post" date: "2024-06-01" --- # Hello from Markdown This is content inside the markdown file.
Example
This example shows how to import a markdown file and render it inside an Astro page. The markdown file has frontmatter and content. The Astro page imports it and displays the markdown content as HTML.
astro + markdown
--- import Post from '../content/post.md'; --- <html lang="en"> <head> <title>Markdown with Astro</title> </head> <body> <h1>Welcome to Astro Markdown Demo</h1> <Post /> </body> </html> // src/content/post.md --- title: "My First Post" date: "2024-06-01" --- # Hello from Markdown This is content inside the markdown file.
Output
<html lang="en">
<head>
<title>Markdown with Astro</title>
</head>
<body>
<h1>Welcome to Astro Markdown Demo</h1>
<h1>Hello from Markdown</h1>
<p>This is content inside the markdown file.</p>
</body>
</html>
Common Pitfalls
Common mistakes when using markdown in Astro include:
- Not placing markdown files in the project folder or wrong import paths.
- Forgetting to use frontmatter
---which can cause parsing errors. - Trying to use markdown content without importing it as a component.
- Not installing necessary Astro markdown support if using MDX features.
Always check your import paths and frontmatter syntax.
astro + javascript
/* Wrong: Trying to use markdown content as a string without import */ const content = `# Title\nContent`; // This won't render as markdown in Astro /* Right: Import markdown as component */ import Content from './content.md'; <Content />
Quick Reference
- Use
import Post from './file.md'to load markdown as a component. - Write frontmatter between
---lines at the top of markdown files. - Render markdown content with
<Post />in Astro pages. - Use
.mdxfiles if you want to embed React components inside markdown. - Ensure your project supports markdown by default or add plugins if needed.
Key Takeaways
Import markdown files as components using
import in Astro.Use frontmatter with
--- to add metadata in markdown files.Render markdown content by placing the imported component in your Astro page.
Check import paths and frontmatter syntax to avoid common errors.
Use
.mdx for combining markdown with interactive components.