Using Markdown Plugins in Astro
Astro uses Remark to render your Markdown which makes it possible to tap into its rich plugin ecosystem. Here, we will learn how to use these plugins on your Astro site.
Let’s start by initializing a project:
npm init astro -- --template blog
Astro config
In the Astro config, add markdownOptions
. Astro comes with a few plugins by default. When we want to add a new plugin, we need to list default plugins in the config. Later, you can remove the plugins that you don’t need:
import { defineConfig } from 'astro/config';
export default defineConfig({
renderers: [],
markdownOptions: {
render: [
'@astrojs/markdown-remark',
{
remarkPlugins: ['remark-gfm', 'remark-smartypants'],
rehypePlugins: ['rehype-slug'],
},
],
},
});
Adding a plugin
Let’s now add a new plugin. I will use remark-toc
as an example.
First, install the plugin:
npm i -D remark-toc
Second, update the config to include the plugin:
import { defineConfig } from 'astro/config';
export default defineConfig({
renderers: [],
markdownOptions: {
render: [
'@astrojs/markdown-remark',
{
remarkPlugins: [
// Other remark plugins…
'remark-toc',
],
// Rehype plugins…
},
],
},
});
Using the plugin
Now let’s use the plugin. Add a few headings to the pages/posts/index.md
file:
<Cool name={frontmatter.name} href="https://twitter.com/n_moore" client:load />
This is so cool!
Do variables work {frontmatter.value \* 2}?
## TOC
## Plants
## Animals
### Cats
### Dogs
``
This should make the plugin generate a table of contents.
Plugin configuration
You can also configurate plugins. Replace a string with a two-item array in the config, and then pass the options inside curly braces:
import { defineConfig } from 'astro/config';
export default defineConfig({
markdown: {
render: [
'@astrojs/markdown-remark',
{
remarkPlugins: [
// Other remark plugins
['remark-toc', { ordered: true }],
],
// Rehype plugins
},
],
},
});
This will make the plugin generate the table of contents as an ordered list.