Created
December 7, 2020 01:36
-
-
Save montanaflynn/9b7d7accffab6ff48c151677112ef6fd to your computer and use it in GitHub Desktop.
Eleventy config to rewrite links
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const markdownIt = require("markdown-it"); | |
const markdownItReplaceLink = require('markdown-it-replace-link'); | |
module.exports = function(eleventyConfig) { | |
let markdownItOptions = { | |
html: true, | |
breaks: true, | |
linkify: true, | |
replaceLink: function (link, env) { | |
link = link.toLowerCase() | |
const doNothing = ['http://', 'https://', '#', 'mailto:']; | |
if (doNothing.some((protocol) => link.startsWith(protocol))) { return link; } | |
// Convert links such as `/page.md` to `/page/` | |
if (link.startsWith("/")) { | |
const extensions = ['md', 'mmd', 'mdl', 'markdown'] | |
if (extensions.some((ext) => link.endsWith(ext))) { | |
const regex = /(?!(?:http:|https:))(.*?)(.md)/gm; | |
const newLink = link.replace(regex, "$1") | |
return newLink | |
} | |
} | |
// Convert links such as `./page.md` to `.././page/` | |
const extensions = ['md', 'mmd', 'mdl', 'markdown'] | |
if (extensions.some((ext) => link.endsWith(ext))) { | |
const regex = /(?!(?:http:|https:))(.*?)(.md)/gm; | |
const lastSegment = env.page.filePathStem.split('/').slice(-1)[0].toLowerCase() | |
if (link.endsWith("index.md")) { | |
link = link.substring(0, link.indexOf("index.md")) | |
} | |
if (lastSegment === "index") { | |
return link.replace(regex, "$1") | |
} | |
return link.replace(regex, "../$1") | |
} | |
return link | |
} | |
}; | |
let md = markdownIt(markdownItOptions) | |
md.use(markdownItReplaceLink) | |
return {}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment