a6e5135765
Co-authored-by: Bjorn Lu <bjornlu.dev@gmail.com> Co-authored-by: Yan Thomas <61414485+Yan-Thomas@users.noreply.github.com> Co-authored-by: Chris Swithinbank <swithinbank@gmail.com> |
||
---|---|---|
.. | ||
components | ||
src | ||
template | ||
test | ||
CHANGELOG.md | ||
package.json | ||
README.md | ||
tsconfig.json |
@astrojs/markdoc (experimental) 📝
This Astro integration enables the usage of Markdoc to create components, pages, and content collection entries.
Why Markdoc?
Markdoc allows you to enhance your Markdown with Astro components. If you have existing content authored in Markdoc, this integration allows you to bring those files to your Astro project using content collections.
Installation
Quick Install
The astro add
command-line tool automates the installation for you. Run one of the following commands in a new terminal window. (If you aren't sure which package manager you're using, run the first command.) Then, follow the prompts, and type "y" in the terminal (meaning "yes") for each one.
# Using NPM
npx astro add markdoc
# Using Yarn
yarn astro add markdoc
# Using PNPM
pnpm astro add markdoc
If you run into any issues, feel free to report them to us on GitHub and try the manual installation steps below.
Manual Install
First, install the @astrojs/markdoc
package using your package manager. If you're using npm or aren't sure, run this in the terminal:
npm install @astrojs/markdoc
Then, apply this integration to your astro.config.*
file using the integrations
property:
// astro.config.mjs
import { defineConfig } from 'astro/config';
import markdoc from '@astrojs/markdoc';
export default defineConfig({
// ...
integrations: [markdoc()],
});
Editor Integration
VS Code supports Markdown by default. However, for Markdoc editor support, you may wish to add the following setting in your VSCode config. This ensures authoring Markdoc files provides a Markdown-like editor experience.
{
"files.associations": {
"*.mdoc": "markdown"
}
}
Usage
Markdoc files can only be used within content collections. Add entries to any content collection using the .mdoc
extension:
src/content/docs/
why-markdoc.mdoc
quick-start.mdoc
Then, query your collection using the Content Collection APIs:
---
import { getEntryBySlug } from 'astro:content';
const entry = await getEntryBySlug('docs', 'why-markdoc');
const { Content } = await entry.render();
---
<!--Access frontmatter properties with `data`-->
<h1>{entry.data.title}</h1>
<!--Render Markdoc contents with the Content component-->
<Content />
📚 See the Astro Content Collection docs for more information.
Markdoc config
@astrojs/markdoc
offers configuration options to use all of Markdoc's features and connect UI components to your content.
Use Astro components as Markdoc tags
You can configure Markdoc tags that map to .astro
components. You can add a new tag by creating a markdoc.config.mjs|ts
file at the root of your project and configuring the tag
attribute.
This example renders an Aside
component, and allows a type
prop to be passed as a string:
// markdoc.config.mjs
import { defineMarkdocConfig, component } from '@astrojs/markdoc/config';
export default defineMarkdocConfig({
tags: {
aside: {
render: component('./src/components/Aside.astro'),
attributes: {
// Markdoc requires type defs for each attribute.
// These should mirror the `Props` type of the component
// you are rendering.
// See Markdoc's documentation on defining attributes
// https://markdoc.dev/docs/attributes#defining-attributes
type: { type: String },
},
},
},
});
This component can now be used in your Markdoc files with the {% aside %}
tag. Children will be passed to your component's default slot:
# Welcome to Markdoc 👋
{% aside type="tip" %}
Use tags like this fancy "aside" to add some _flair_ to your docs.
{% /aside %}
Use Astro components from npm packages and TypeScript files
You may need to use Astro components exposed as named exports from TypeScript or JavaScript files. This is common when using npm packages and design systems.
You can pass the import name as the second argument to the component()
function:
// markdoc.config.mjs
import { defineMarkdocConfig, component } from '@astrojs/markdoc/config';
export default defineMarkdocConfig({
tags: {
tabs: {
render: component('@astrojs/starlight/components', 'Tabs'),
},
},
});
This generates the following import statement internally:
import { Tabs } from '@astrojs/starlight/components';
Custom headings
@astrojs/markdoc
automatically adds anchor links to your headings, and generates a list of headings
via the content collections API. To further customize how headings are rendered, you can apply an Astro component as a Markdoc node.
This example renders a Heading.astro
component using the render
property:
// markdoc.config.mjs
import { defineMarkdocConfig, nodes, component } from '@astrojs/markdoc/config';
export default defineMarkdocConfig({
nodes: {
heading: {
...nodes.heading, // Preserve default anchor link generation
render: component('./src/components/Heading.astro'),
},
},
});
All Markdown headings will render the Heading.astro
component and pass the following attributes
as component props:
level: number
The heading level 1 - 6id: string
Anid
generated from the heading's text contents. This corresponds to theslug
generated by the contentrender()
function.
For example, the heading ### Level 3 heading!
will pass level: 3
and id: 'level-3-heading'
as component props.
Syntax highlighting
@astrojs/markdoc
provides Shiki and Prism extensions to highlight your code blocks.
Shiki
Apply the shiki()
extension to your Markdoc config using the extends
property. You can optionally pass a shiki configuration object:
// markdoc.config.mjs
import { defineMarkdocConfig } from '@astrojs/markdoc/config';
import shiki from '@astrojs/markdoc/shiki';
export default defineMarkdocConfig({
extends: [
shiki({
// Choose from Shiki's built-in themes (or add your own)
// Default: 'github-dark'
// https://github.com/shikijs/shiki/blob/main/docs/themes.md
theme: 'dracula',
// Enable word wrap to prevent horizontal scrolling
// Default: false
wrap: true,
// Pass custom languages
// Note: Shiki has countless langs built-in, including `.astro`!
// https://github.com/shikijs/shiki/blob/main/docs/languages.md
langs: [],
}),
],
});
Prism
Apply the prism()
extension to your Markdoc config using the extends
property.
// markdoc.config.mjs
import { defineMarkdocConfig } from '@astrojs/markdoc/config';
import prism from '@astrojs/markdoc/prism';
export default defineMarkdocConfig({
extends: [prism()],
});
📚 To learn about configuring Prism stylesheets, see our syntax highlighting guide.
Set the root HTML element
Markdoc wraps documents with an <article>
tag by default. This can be changed from the document
Markdoc node. This accepts an HTML element name or null
if you prefer to remove the wrapper element:
// markdoc.config.mjs
import { defineMarkdocConfig, nodes } from '@astrojs/markdoc/config';
export default defineMarkdocConfig({
nodes: {
document: {
...nodes.document, // Apply defaults for other options
render: null, // default 'article'
},
},
});
Custom Markdoc nodes / elements
You may want to render standard Markdown elements, such as paragraphs and bolded text, as Astro components. For this, you can configure a Markdoc node. If a given node receives attributes, they will be available as component props.
This example renders blockquotes with a custom Quote.astro
component:
// markdoc.config.mjs
import { defineMarkdocConfig, nodes, component } from '@astrojs/markdoc/config';
export default defineMarkdocConfig({
nodes: {
blockquote: {
...nodes.blockquote, // Apply Markdoc's defaults for other options
render: component('./src/components/Quote.astro'),
},
},
});
📚 Find all of Markdoc's built-in nodes and node attributes on their documentation.
Use client-side UI components
Tags and nodes are restricted to .astro
files. To embed client-side UI components in Markdoc, use a wrapper .astro
component that renders a framework component with your desired client:
directive.
This example wraps a React Aside.tsx
component with a ClientAside.astro
component:
---
// src/components/ClientAside.astro
import Aside from './Aside';
---
<Aside {...Astro.props} client:load />
This Astro component can now be passed to the render
prop for any tag or node in your config:
// markdoc.config.mjs
import { defineMarkdocConfig, component } from '@astrojs/markdoc/config';
export default defineMarkdocConfig({
tags: {
aside: {
render: component('./src/components/ClientAside.astro'),
attributes: {
type: { type: String },
},
},
},
});
Markdoc config
The markdoc.config.mjs|ts
file accepts all Markdoc configuration options, including tags and functions.
You can pass these options from the default export in your markdoc.config.mjs|ts
file:
// markdoc.config.mjs
import { defineMarkdocConfig } from '@astrojs/markdoc/config';
export default defineMarkdocConfig({
functions: {
getCountryEmoji: {
transform(parameters) {
const [country] = Object.values(parameters);
const countryToEmojiMap = {
japan: '🇯🇵',
spain: '🇪🇸',
france: '🇫🇷',
};
return countryToEmojiMap[country] ?? '🏳';
},
},
},
});
Now, you can call this function from any Markdoc content entry:
¡Hola {% getCountryEmoji("spain") %}!
📚 See the Markdoc documentation for more on using variables or functions in your content.
Pass Markdoc variables
You may need to pass variables to your content. This is useful when passing SSR parameters like A/B tests.
Variables can be passed as props via the Content
component:
---
import { getEntryBySlug } from 'astro:content';
const entry = await getEntryBySlug('docs', 'why-markdoc');
const { Content } = await entry.render();
---
<!--Pass the `abTest` param as a variable-->
<Content abTestGroup={Astro.params.abTestGroup} />
Now, abTestGroup
is available as a variable in docs/why-markdoc.mdoc
:
{% if $abTestGroup === 'image-optimization-lover' %}
Let me tell you about image optimization...
{% /if %}
To make a variable global to all Markdoc files, you can use the variables
attribute from your markdoc.config.mjs|ts
:
import { defineMarkdocConfig } from '@astrojs/markdoc/config';
export default defineMarkdocConfig({
variables: {
environment: process.env.IS_PROD ? 'prod' : 'dev',
},
});
Access frontmatter from your Markdoc content
To access frontmatter, you can pass the entry data
property as a variable where you render your content:
---
import { getEntry } from 'astro:content';
const entry = await getEntry('docs', 'why-markdoc');
const { Content } = await entry.render();
---
<Content frontmatter={entry.data} />
This can now be accessed as $frontmatter
in your Markdoc.
Integration config options
The Astro Markdoc integration handles configuring Markdoc options and capabilities that are not available through the markdoc.config.js
file.
allowHTML
Enables writing HTML markup alongside Markdoc tags and nodes.
By default, Markdoc will not recognize HTML markup as semantic content.
To achieve a more Markdown-like experience, where HTML elements can be included alongside your content, set allowHTML:true
as a markdoc
integration option. This will enable HTML parsing in Markdoc markup.
// astro.config.mjs
import { defineConfig } from 'astro/config';
import markdoc from '@astrojs/markdoc';
export default defineConfig({
// ...
integrations: [markdoc({ allowHTML: true })],
});
Warning
When
allowHTML
is enabled, HTML markup inside Markdoc documents will be rendered as actual HTML elements (including<script>
), making attack vectors like XSS possible. Ensure that any HTML markup comes from trusted sources.
Examples
- The Astro Markdoc starter template shows how to use Markdoc files in your Astro project.
Troubleshooting
For help, check out the #support
channel on Discord. Our friendly Support Squad members are here to help!
You can also check our Astro Integration Documentation for more on integrations.
Contributing
This package is maintained by Astro's Core team. You're welcome to submit an issue or PR!
Changelog
See CHANGELOG.md for a history of changes to this integration.