Last active
December 22, 2023 15:10
-
-
Save solace/aaeaa3e8f60c4dfddfc45f6f3ebe0b50 to your computer and use it in GitHub Desktop.
Image colocation support in eleventy. See https://micheleong.com/2023/09/23/migrate-wordpress-eleventy-colocated-images
This file contains 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
// 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