Skip to content

Commit 8682b3e

Browse files
Implement relative path support for mdx link resolving
1 parent cd3b439 commit 8682b3e

File tree

3 files changed

+13
-6
lines changed

3 files changed

+13
-6
lines changed

posts/5.md

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Animation where only input is time. Once per year something interesting happens

src/render.tsx

+3-2
Original file line numberDiff line numberDiff line change
@@ -249,12 +249,13 @@ async function getPostData(
249249
const { data, content } = await parseMdxFile(mdxFilePath);
250250
const plain = remark().use(stripMarkdown).processSync(content).toString();
251251

252+
const postPath = `/posts/${data.slug}/`;
252253
const renderedMdxSource = await renderMdxToString(content, {
253254
components: {
254255
...COMPONENTS,
255256
},
256257
mdxOptions: {
257-
remarkPlugins: [resolveLinks],
258+
remarkPlugins: [[resolveLinks, { currentPath: postPath }]],
258259
},
259260
});
260261
const charCount = plain.replace(/\s+/, "").length;
@@ -267,7 +268,7 @@ async function getPostData(
267268
slug: data.slug,
268269
tags: data.tags,
269270
description: data.description,
270-
path: `/posts/${data.slug}`,
271+
path: postPath,
271272
charCount,
272273
html: renderedMdxSource.renderedOutput,
273274
};

src/util/remark-resolve-links.ts

+9-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
import visit from "unist-util-visit";
22

3-
export function resolveLinks() {
3+
type Options = {
4+
currentPath?: string;
5+
};
6+
7+
export function resolveLinks(opts: Options = { currentPath: "/" }) {
48
return (tree: any) => {
59
// Visit all nodes that have .url attribute
610
// https://github.com/syntax-tree/mdast
@@ -14,9 +18,10 @@ export function resolveLinks() {
1418
return;
1519
}
1620

17-
if (linkUrl.startsWith("/")) {
18-
node.url = `https://kimmo.blog${node.url}`;
19-
}
21+
node.url = new URL(
22+
linkUrl,
23+
`https://kimmo.blog${opts.currentPath}`
24+
).toString();
2025
});
2126
};
2227
}

0 commit comments

Comments
 (0)