Skip to content

Instantly share code, notes, and snippets.

@solace
Last active December 22, 2023 15:10
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 solace/aaeaa3e8f60c4dfddfc45f6f3ebe0b50 to your computer and use it in GitHub Desktop.
Save solace/aaeaa3e8f60c4dfddfc45f6f3ebe0b50 to your computer and use it in GitHub Desktop.
// Import this
const modifyToken = require('markdown-it-modify-token');
module.exports = function (config) {
...
// Pass a custom instance of markdownIt into eleventy.
config.setLibrary("md", markdownIt({
// html, breaks, and linkify are default options from eleventy.
html: true,
breaks: true,
linkify: true,
// This will prepend the colocated image path with the built asset path
modifyToken: function (token, env) {
switch (token.type) {
case 'image':
// Only apply this transform to relative image path
// Regex explained: https://regex101.com/r/EM83AR/1
if (token.attrObj.src.match(/^(?!www\.|(?:http|ftp)s?:\/\/|[A-Za-z]:\\|\/).*/)) {
// https://www.11ty.dev/docs/data-eleventy-supplied/#filepathstem
const stem = env.page.filePathStem.split(path.sep);
stem.pop();
token.attrObj.src = path.resolve(stem.join(path.sep), token.attrObj.src);
}
break;
}
}
})
.use(modifyToken)
);
// This copies your images from where they are colocated to a similarly pathed location in `dist`
// It allows the modifyToken above and colocatedImagePath filter below to work.
config.addPassthroughCopy('src/posts/**/images/*');
// This adds a filter that performs a similar transform as modifyToken that you can use in templates
config.addFilter('colocatedImagePath', (src, filePathStem) => {
const stem = filePathStem.split(path.sep);
stem.pop();
return src ? path.resolve(stem.join(path.sep), src) : '/assets/img/no-image.svg';
});
...
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment