From 7f37604afd9f112a5cdb328c0aa54f65186c3c4e Mon Sep 17 00:00:00 2001 From: Divyansh Singh <40380293+brc-dd@users.noreply.github.com> Date: Thu, 20 Jan 2022 10:09:01 +0530 Subject: [PATCH] fix: append base to links --- src/node/markdown/markdown.ts | 17 +++++++++++------ src/node/markdown/plugins/link.ts | 8 +++++++- src/node/markdownToVue.ts | 5 +++-- src/node/plugin.ts | 3 ++- 4 files changed, 23 insertions(+), 10 deletions(-) diff --git a/src/node/markdown/markdown.ts b/src/node/markdown/markdown.ts index 1fdb926814ae..c9d68b9ec862 100644 --- a/src/node/markdown/markdown.ts +++ b/src/node/markdown/markdown.ts @@ -49,7 +49,8 @@ export type { Header } export const createMarkdownRenderer = ( srcDir: string, - options: MarkdownOptions = {} + options: MarkdownOptions = {}, + base: string ): MarkdownRenderer => { const md = MarkdownIt({ html: true, @@ -66,11 +67,15 @@ export const createMarkdownRenderer = ( .use(hoistPlugin) .use(containerPlugin) .use(headingPlugin) - .use(linkPlugin, { - target: '_blank', - rel: 'noopener noreferrer', - ...options.externalLinks - }) + .use( + linkPlugin, + { + target: '_blank', + rel: 'noopener noreferrer', + ...options.externalLinks + }, + base + ) // 3rd party plugins .use(attrs, options.attrs) .use(anchor, { diff --git a/src/node/markdown/plugins/link.ts b/src/node/markdown/plugins/link.ts index e44c043a14d6..d1448bc803e5 100644 --- a/src/node/markdown/plugins/link.ts +++ b/src/node/markdown/plugins/link.ts @@ -11,7 +11,8 @@ const indexRE = /(^|.*\/)index.md(#?.*)$/i export const linkPlugin = ( md: MarkdownIt, - externalAttrs: Record + externalAttrs: Record, + base: string ) => { md.renderer.rules.link_open = (tokens, idx, options, env, self) => { const token = tokens[idx] @@ -76,6 +77,11 @@ export const linkPlugin = ( // export it for existence check pushLink(url.replace(/\.html$/, '')) + // append base to internal (non-relative) urls + if (url.startsWith('/')) { + url = `${base}${url}`.replace(/\/+/g, '/') + } + // markdown-it encodes the uri hrefAttr[1] = decodeURI(url) } diff --git a/src/node/markdownToVue.ts b/src/node/markdownToVue.ts index a596e22bfc3d..c969c152d482 100644 --- a/src/node/markdownToVue.ts +++ b/src/node/markdownToVue.ts @@ -25,9 +25,10 @@ export function createMarkdownToVueRenderFn( options: MarkdownOptions = {}, pages: string[], userDefines: Record | undefined, - isBuild = false + isBuild = false, + base: string ) { - const md = createMarkdownRenderer(srcDir, options) + const md = createMarkdownRenderer(srcDir, options, base) pages = pages.map((p) => slash(p.replace(/\.md$/, ''))) const userDefineRegex = userDefines diff --git a/src/node/plugin.ts b/src/node/plugin.ts index fc6d8e6fd146..7f253d06ac26 100644 --- a/src/node/plugin.ts +++ b/src/node/plugin.ts @@ -84,7 +84,8 @@ export function createVitePressPlugin( markdown, pages, config.define, - config.command === 'build' + config.command === 'build', + config.base ) },