11ty / eleventy-fetch

Utility to cache any remote asset: Image, Video, Web Font, CSS, JSON, etc
https://www.11ty.dev/docs/plugins/fetch/
144 stars 19 forks source link

Read from cache when watching #47

Closed groenroos closed 1 week ago

groenroos commented 2 months ago

Is it possible to configure fetch to always load from remote when doing the initial build (effectively duration: '0s'), but then always read from cache when the site is re-built via live reload (i.e. when running Eleventy with the --watch flag)?

We're using fetch to get content from an external CMS, and while always fetching the latest data in the initial build is important (so we have the latest content to work against), I'd want subsequent live re-builds to read from cache, so that some simple template tweak doesn't take 14s+ to build when every CMS endpoint is hit again.

Zegnat commented 1 month ago

I do not think eleventy-fetch can see what is going on build-wise.

But would this be solved by making sure you empty the cache folder before you start the build? Then it should only fill the cache once at the start. You could use something like rimraf right at the start of your build-watch process.

zachleat commented 1 week ago

If you want to make it a little less expensive, you can use either Eleventy provided environment variables or events to do this:

Never use cache on build, always use cache on watch/serve

https://www.11ty.dev/docs/environment-vars/#eleventy-supplied

await EleventyFetch("https://example.com", {
    duration: process.env.ELEVENTY_RUN_MODE === "build" ? "0s" : "*"
});

Always fetch on first build (even during serve/watch)

https://www.11ty.dev/docs/events/#eleventy.before

export default function(eleventyConfig) {
    let buildCount = 0;
    process.env.BUILD_COUNT = buildCount;

    eleventyConfig.on("eleventy.before", () => {
        process.env.BUILD_COUNT = ++buildCount;
    });
}
await EleventyFetch("https://example.com", {
    duration: process.env.BUILD_COUNT === 1 ? "0s" : "*"
});