11ty / eleventy-img

Utility to perform build-time image transformations.

Home Page:https://www.11ty.dev/docs/plugins/image/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Allow creation of folders for converted images

danburzo opened this issue · comments

The part that writes files to disk currently relies on the folders to already exist:

outputFilePromises.push(fsp.writeFile(stat.outputPath, hookResult).then(() => stat));

It would be great for eleventy-img to automatically create any folders needed along the output path with something like:

outputFilePromises.push(
    fsp.mkdir(path.dirname(stat.outputPath), { recursive: true })
    .then(() => fsp.writeFile(stat.outputPath, hookResult))
    .then(() => stat)
); 

This would enable more flexibility on where to place the converted files. For example, I'd like to isolate them into their own _optimized folder adjacent to the source files, that I can delete in one fell swoop whenever needed.

Sample code:

let metadata = await Image(inputPath, {
	formats: ['avif', 'webp', 'jpeg'],
	widths: [1000, 800, 400],
	outputDir: 'static/img',
	filenameFormat: function(id, src, width, format, options) {
		const dir = path.relative('static/img', path.dirname(src));
		const name = path.basename(src, path.extname(src));
		return path.join(dir, '_optimized', `${name}-w${width}.${format}`);
	}
});

I've created, for convenience, a PR with the suggested changes.

I ran into this limitation today, would love to see this supported!