Skip to content

Instantly share code, notes, and snippets.

@lukaskoeller
Last active January 25, 2023 14:32
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 lukaskoeller/05feac3f04c212ad927c5a4b74b9d915 to your computer and use it in GitHub Desktop.
Save lukaskoeller/05feac3f04c212ad927c5a4b74b9d915 to your computer and use it in GitHub Desktop.
Build image map making use of vite-imagetools
const fs = require('fs');
const path = require('path');
const directoryPath = './src/assets/images';
const outputPath = './src/assets/images/index.ts';
const imageExtensions = ['png', 'jpg', 'jpeg', 'gif'];
const CONSULTANT_IMPORT_SET = [];
const CONSULTANT_IMG_MAP = [];
const PATH_TO_IMAGE = './';
const IMG_SIZE = 64;
fs.readdir(directoryPath, (err, files) => {
if (err) {
console.log('Error reading directory: ', err);
return;
}
files.forEach((file) => {
const fileExtension = path.extname(file).substring(1);
if (imageExtensions.includes(fileExtension)) {
const filename = path.basename(file, `.${fileExtension}`);
const [
importNameAvif,
importNameWebp,
importNameJpg,
] = [
`img${filename}Avif`,
`img${filename}Webp`,
`img${filename}Jpg`,
];
const importAvif = `import ${importNameAvif} from '${PATH_TO_IMAGE}${filename}.${fileExtension}?w=${IMG_SIZE};${IMG_SIZE * 1.5};${IMG_SIZE * 2}&avif&source';`;
const importWebp = `import ${importNameWebp} from '${PATH_TO_IMAGE}${filename}.${fileExtension}?w=${IMG_SIZE};${IMG_SIZE * 1.5};${IMG_SIZE * 2}&webp&source';`;
const importJpg = `import ${importNameJpg} from '${PATH_TO_IMAGE}${filename}.${fileExtension}?w=${IMG_SIZE}&jpg';`;
CONSULTANT_IMPORT_SET.push(`${importAvif}\n${importWebp}\n${importJpg}`);
CONSULTANT_IMG_MAP.push(` '${filename}': {
avif: ${importNameAvif},
webp: ${importNameWebp},
jpg: ${importNameJpg},
},`);
}
});
const outputString = `// @ts-nocheck
/* eslint-disable import/no-unresolved */
/**
*
* 'Unable to resolve path' error is currently an open issue:
* @see https://github.com/JonasKruckenberg/imagetools/issues/70
*/
${CONSULTANT_IMPORT_SET.join('\n')}
export const CONSULTANT_IMG_MAP: Record<string, {
avif: { src: string, w: number }[];
webp: { src: string, w: number }[];
jpg: string;
}> = {
${CONSULTANT_IMG_MAP.join('\n')}
};
`;
fs.writeFile(outputPath, outputString, (writeErr) => {
if (writeErr) {
console.log('Error writing file: ', writeErr);
} else {
console.log(`Successfully created file at ${outputPath}`);
}
});
});
{
"name": "image-vite-imagetools-map",
"version": "1.0.0",
"bin": "./index.js"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment