This is a rehype plugin built for Astro that aims to transform relative links in MD and MDX files into their final output paths.
🚨 This is experimental and build exclusively for Astro. I have made a couple assumptions. They are:
- You are rendering a static site (i.e. not using SSR)
- You have a content collection residing at
src/content/<content_collection>
- You have a page that renders the above content collection at
src/pages/<content_collection>/[...slug].astro
If you have a markdown files at src/content/blog/post.md
with the content of:
[relative link](./other-markdown.md)
The resulting HTML should be:
<a href="/blog/other-markdown">relative link</a>
It supports links with Query Strings and Hashes (e.g. [relative link](./other-markdown.md?query=test#hash)
).
Tested with Node.js v18 and Astro 2.x.
- MacOS (Ventura)
- Windows (Windows 11)
- Linux (Debian 11)
Yarn
yarn add astro-rehype-relative-markdown-links
PNPM
pnpm add astro-rehype-relative-markdown-links
NPM
npm install astro-rehype-relative-markdown-links
astro.config.mjs
import rehypeAstroRelativeMarkdownLinks from "astro-rehype-relative-markdown-links";
// ...everything else
export default defineConfig({
// ...everything else
markdown: {
rehypePlugins: [rehypeAstroRelativeMarkdownLinks],
},
});
Using Yarn in example (sorry).
DEBUG=astro-rehype-relative-markdown-links yarn build
# or
DEBUG=astro-rehype-relative-markdown-links yarn dev
- I'm currently using this in my blog. Use it as an example if it's easier!
- This rehype plugin was called
rehype-astro-relative-markdown-links
in the past. I've changed this due to rehype's naming guidelines.