Skip to content

Commit 583f27f

Browse files
committed
Resolve relative URLs in Markdown output for links and images
1 parent 0aac7e8 commit 583f27f

1 file changed

Lines changed: 25 additions & 2 deletions

File tree

astro/src/plugins/markdown-output.ts

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,14 @@ import { toText } from "hast-util-to-text";
1818
* components, etc. are already resolved.
1919
*/
2020
export default function markdownOutput() {
21+
let siteUrl = "";
22+
2123
return {
2224
name: "markdown-output",
2325
hooks: {
26+
"astro:config:done": ({ config }: { config: { site?: string } }) => {
27+
siteUrl = config.site ? new URL(config.site).origin : "";
28+
},
2429
"astro:build:done": async ({
2530
dir,
2631
pages,
@@ -147,6 +152,23 @@ export default function markdownOutput() {
147152
// Remove "Edit page" link and "Last updated" meta section
148153
main.querySelectorAll("footer .meta").forEach((el) => el.remove());
149154

155+
// Resolve image paths: /_astro/... URLs are build artifacts;
156+
// rewrite them to absolute URLs so they resolve outside the build output.
157+
main.querySelectorAll("img").forEach((img) => {
158+
const src = img.getAttribute("src");
159+
if (src && src.startsWith("/")) {
160+
img.setAttribute("src", `${siteUrl}${src}`);
161+
}
162+
});
163+
164+
// Resolve link hrefs to absolute URLs
165+
main.querySelectorAll("a").forEach((a) => {
166+
const href = a.getAttribute("href");
167+
if (href && href.startsWith("/")) {
168+
a.setAttribute("href", `${siteUrl}${href}`);
169+
}
170+
});
171+
150172
// Remove giscus comments
151173
main.querySelectorAll("giscus-comments").forEach((el) => el.remove());
152174

@@ -169,9 +191,10 @@ export default function markdownOutput() {
169191
const content = main.innerHTML;
170192
const result = await processor.process(content);
171193

172-
// Add page title as YAML frontmatter
194+
// Add page title and source URL as YAML frontmatter
173195
const pageTitle = doc.querySelector("title")?.textContent?.trim() || "";
174-
const frontmatter = `---\ntitle: ${pageTitle}\n---\n\n`;
196+
const pageSource = siteUrl ? `${siteUrl}/${pathname}` : `/${pathname}`;
197+
const frontmatter = `---\ntitle: ${pageTitle}\nsource: ${pageSource}\n---\n\n`;
175198

176199
await fs.writeFile(mdPath, frontmatter + String(result));
177200
count++;

0 commit comments

Comments
 (0)