Automatic Eleventy Markdown Links in New Tab

I wrote a while back about how to append target="_blank" to links in Markdown. That’s fine for the odd link here and there, but what if you want to have this happen systematically? A realistic example is that you might want all external links (i.e. links to pages on other people’s websites) to open in a new tab.

Good news. You can automate this. Here’s how:

First, install the package:

npm install markdown-it-link-attributes

Then in your eleventy.js file:

const mila = require("markdown-it-link-attributes");

module.exports = function(eleventyConfig) {
  const milaOptions = {
    return href.match(/^https?:\/\//);
    attrs: {
      target: "_blank",
      rel: "noopener"
    }
  };
  eleventyConfig.amendLibrary("md", mdLib => mdLib.use(mila, milaOptions));
};

Here’s my comment on an Eleventy issue in case anyone replies with a better method.