Skip to content

Commit

Permalink
fix: append base to links (#502)
Browse files Browse the repository at this point in the history
fix #252
  • Loading branch information
brc-dd authored Feb 22, 2022
1 parent ffe0c40 commit 804954c
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 8 deletions.
17 changes: 11 additions & 6 deletions src/node/markdown/markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ export type { Header }

export const createMarkdownRenderer = (
srcDir: string,
options: MarkdownOptions = {}
options: MarkdownOptions = {},
base: string
): MarkdownRenderer => {
const md = MarkdownIt({
html: true,
Expand All @@ -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, {
Expand Down
8 changes: 7 additions & 1 deletion src/node/markdown/plugins/link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ const indexRE = /(^|.*\/)index.md(#?.*)$/i

export const linkPlugin = (
md: MarkdownIt,
externalAttrs: Record<string, string>
externalAttrs: Record<string, string>,
base: string
) => {
md.renderer.rules.link_open = (tokens, idx, options, env, self) => {
const token = tokens[idx]
Expand Down Expand Up @@ -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)
}
Expand Down
3 changes: 2 additions & 1 deletion src/node/markdownToVue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,10 @@ export function createMarkdownToVueRenderFn(
pages: string[],
userDefines: Record<string, any> | undefined,
isBuild = false,
base: string,
includeLastUpdatedData = false
) {
const md = createMarkdownRenderer(srcDir, options)
const md = createMarkdownRenderer(srcDir, options, base)
pages = pages.map((p) => slash(p.replace(/\.md$/, '')))

const userDefineRegex = userDefines
Expand Down
1 change: 1 addition & 0 deletions src/node/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ export function createVitePressPlugin(
pages,
config.define,
config.command === 'build',
config.base,
siteConfig.lastUpdated
)
},
Expand Down

0 comments on commit 804954c

Please sign in to comment.