Skip to content

Instantly share code, notes, and snippets.

@montanaflynn
Created December 7, 2020 01:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save montanaflynn/9b7d7accffab6ff48c151677112ef6fd to your computer and use it in GitHub Desktop.
Save montanaflynn/9b7d7accffab6ff48c151677112ef6fd to your computer and use it in GitHub Desktop.
Eleventy config to rewrite links
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