Eleventy: Images Vanishing on Build? Find Them with This Fix
Problem: You've built a beautiful Eleventy website, complete with stunning images. But when you deploy, those images disappear, leaving behind broken links and a frustratingly incomplete website.
Rephrased: Your images are showing up perfectly in your local development environment, but they're missing when you build your Eleventy site. This can be a real head-scratcher!
Scenario and Original Code:
Let's imagine you have a blog post with an image:
<img src="/assets/images/blog-post-image.jpg" alt="A beautiful image">
In your _includes/head.html
, you might have a link to your CSS file:
<link rel="stylesheet" href="/assets/css/styles.css">
And in your eleventy.config.js
, you have a basic configuration:
module.exports = function(config) {
config.addPassthroughCopy("assets");
return {
dir: {
input: "src",
output: "public"
}
};
};
Everything looks correct locally, but upon building your site, the image is missing from the public
directory, causing the broken link.
The Insight: The issue lies in Eleventy's default behavior and how it handles the addPassthroughCopy
method. While it's meant to copy files directly to the output directory, it doesn't always work as expected when dealing with nested folders within your assets
directory.
The Solution:
The most straightforward fix is to use a dedicated plugin for copying assets:
npm install @11ty/eleventy-plugin-asset
Then, modify your eleventy.config.js
:
const assetPlugin = require('@11ty/eleventy-plugin-asset');
module.exports = function(config) {
config.addPlugin(assetPlugin);
return {
dir: {
input: "src",
output: "public"
}
};
};
Now, the asset
plugin will handle copying all your files from the assets
directory to the public
folder during the build process, ensuring your images and other assets are correctly included in your deployed site.
Additional Value:
This solution not only fixes the image issue but also ensures that all your assets are managed consistently and efficiently, removing the need for manual copying or complex configuration. This approach will save you time and effort, especially as your project grows and you need to manage more files.
References:
- @11ty/eleventy-plugin-asset: https://www.npmjs.com/package/@11ty/eleventy-plugin-asset
- Eleventy Documentation: https://www.11ty.dev/docs/
Key Takeaways:
- The
addPassthroughCopy
method in Eleventy might not always work as expected with nested folders. - The
@11ty/eleventy-plugin-asset
provides a reliable and simple solution for managing assets in your Eleventy project. - By utilizing this plugin, you ensure consistent and efficient asset handling, simplifying your workflow and reducing potential errors.