Is it possible for webpack to import static files using a dynamic path?

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?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Change the type of an object to a different type

Within my class, I have set the type of range to IntervalRange. export class Test {range: IntervalRange;} Then, in the parent class, I initialize the value: export class TestInitializer { Create(){ return <Test>{ range: IntervalRange.i ...

Is there a way to customize the slicing of *ngFor in a component according to the components it is being injected into?

This code snippet represents a component that needs to be included in other components: <div class="row"> <div class="col-12 [...]" *ngFor="let course of courses"> <div class="card"> ...

What is the best way to handle commas within CSV values when importing a table into MySQL?

I'm having trouble figuring out the best way to import a CSV file into a MySQL database table. The format of the CSV rows I am dealing with is as follows: "00602"," ","42042","15590","0","0","0","35","9","67","1978","20608","21434","3.1","54700","113 ...

I need to compile a comprehensive inventory of all the publicly accessible attributes belonging to a Class/Interface

When working with TypeScript, one of the advantages is defining classes and their public properties. Is there a method to list all the public properties associated with a particular class? class Car { model: string; } let car:Car = new Car(); Object. ...

Configuring Webpack for a React application with Express and Babel

I am in the process of developing a React application, utilizing React version ^15.6.1 along with Webpack, Express, Babel, and Yarn as the package manager. After successfully running the application, I am now preparing to transition it to production by co ...

Struggling to obtain the Variable

Trying to send a POST request to my ESP8266 HTTP Server, I need to transmit 4 variables: onhour, offhour, onminute, offminute. These variables should be retrieved from a timepicker-component imported from "ng-bootstrap" Despite numerous attempts over the ...

When the button is pressed, the TypeScript observable function will return a value

Check out the snippet of code I'm working with: removeAlert() : Observable<boolean> { Swal.fire({ title: 'delete this file ?', text: 'sth', icon: 'warning', showCancelButton: true, ...

The error message "Undefined value received instead of a string or boolean in Vuetify and nuxt.js rules" indicates that the expected data type was not provided

I recently created an app at my workplace and encountered an error in the text area similar to what I have described in my title. After researching the issue online, I found some information but still struggle to fully grasp the concept. My objective is t ...

Troubleshooting Issue with Angular Library: Live Reload Feature Not Functioning

In setting up my Angular workspace, I have 3 libraries and one application (with more to be added in the future). This is how the TypeScript paths are configured: "paths": { "@lib/a/*": [ "projects/libs/a/*", ...

What benefits could be gained from enabling the compiler option "declaration" in a TypeScript project?

I am currently working on a TypeScript project and contemplating the possibility of publishing it as an NPM package in the future. Currently, I have the "declaration": true setting in my tsconfig.json, which is causing some issues that are irrelevant to t ...

Determining the size of a custom-typed array in Typescript

Can anyone explain how to find the length of a custom typed array? For example: type TMyArray = IProduct[] interface IProduct { cost: number, name: string, weight: number } So, how can we determine the length in this case: const testArr: TMyArray ...

Identifying digits and letters by processing individual user input

I am facing a coding challenge with the following code snippet: <div class="form-group"> <label for="txtName">Name</label> <input type="text" pInputText class="form-control" id="txtName" formControlName="name"> < ...

Make sure the subset interface is selected from the interface / Choose PickDeep<>?

I am searching for a solution using the following interface: interface Person { age: number, name: string, hometown?: { city: string, zip: number } } type SubPerson = EnsureSubInterface<Person, { name: string }> an example that w ...

Setting up the TypeScript compiler locally in the package.json file

UPDATE #1: It appears that I have managed to come up with a functional configuration, but I am open to any suggestions for improvement. Feel free to check out the answer here: THE ORIGINAL INQUIRY: I am in the process of setting up my environment so that ...

Encountering the issue: "Error: Unable to locate preset "env" in relation to the current directory"

Encountering the following error message Error: Couldn't find preset "env" relative to directory when trying to run my project using either npm run dev or npm run build I would greatly appreciate any assistance, as I have been struggling with this is ...

Styling in Svelte/TS does not change when applied through a foreach loop

I've been experimenting with creating a unique "bubble" effect on one of my websites, but I'm facing difficulty changing the styling in a foreach loop. Despite no errors showing up in the console, I'm at a loss as to how to effectively debu ...

What is the method for adjusting the spacing between binding tags within HTML code formatting specifically for TypeScript elements in IntelliJ?

My Angular binding currently defaults to <h1>{{typeScriptVar}}</h1>, but I would like it to be set as <h1>{{ typeScriptVar }}</h1> when I use the format code shortcut in InteliJ. Can anyone assist me with this issue? I have resear ...

No bugs appeared in Next.js

I am currently in the process of migrating a large create-react-app project to NextJS. To do this, I started a new Next project using create-next-app and am transferring all the files over manually. The main part of my page requires client-side rendering f ...

Fastify Typescript: dealing with an unidentified body

I'm new to Fastify and I've encountered a problem with accessing values in the body using Typescript. Does anyone have any ideas or suggestions? Thanks! Update: I want to simplify my code and avoid using app.get(...) Here's my code snippet ...

Using JSON to dynamically generate pages in Gatsby programatically

Currently, I am utilizing Gatsby to dynamically generate pages, and I am looking to do so at two distinct paths: covers/{json.name}.js and styles/{json.name}.js. While I have successfully set this up using the gatsby-node.js file, I would like to transit ...