Currently, I am working on a project that involves TypeScript, Webpack, React, and Gatsby. My goal is to import multiple images with various resolutions and webp versions to enhance performance.
I have started importing the images in this manner:
import Project1Screenshot640 from './images/projects/screenshots/640/project1.jpg'
import Project1Screenshot1280 from './images/projects/screenshots/1280/project1.jpg'
import Project1Screenshot1526 from './images/projects/screenshots/1526/project1.jpg'
import Project1Screenshot640Webp from './images/projects/screenshots/640/project1.webp'
import Project1Screenshot1280Webp from './images/projects/screenshots/1280/project1.webp'
import Project1Screenshot1526Webp from './images/projects/screenshots/1526/project1.webp'
// ... (additional imports)
const projects = {
'project-1': {
title: 'Project 1',
screenshot: {
640: [Project1Screenshot640, Project1Screenshot640Webp],
1280: [Project1Screenshot1280, Project1Screenshot1280Webp],
1526: [Project1Screenshot1526, Project1Screenshot1526Webp],
},
},
// ...
}
However, I've realized that managing these imports manually is not sustainable and it would be more efficient to generate them during compilation.
It would be ideal to implement something like the following...
const generateProject = (id, title) => {
import Screenshot640 from `./images/projects/screenshots/640/${id}.jpg`
// ...
import Screenshot640Webp from `./images/projects/screenshots/640/${id}.webp`
// ...
return {
title,
screenshot: [
640: [Screenshot640, Screenshot640Webp],
// ...
],
}
}
const projects = {
'project-1': generateProject('project-1', 'Project 1')
}
Unfortunately, importing with dynamic paths synchronously seems to pose some challenges without asynchronous methods like
const Screenshot640 = await import('...')
.
Is there any way to automate the generation of project imports using webpack/gatsby during the build process so they are included in the compiled code?