Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

97
Views
Dynamically create import statements from src's inside a JSON file for webpack build

I have an example JSON file like the following:

menu.json

{
  "0":{
      "img":"./101 cup noodles.png"
  },
  "1":{
      "img":"./102 cup noodles with beef.png"
  },
  "2":{
      "img":"./103 cup noodles with egg.png"
  },
  "3":{
      "img":"./104 cup noodles with shrimp.png"
  }
}

Is there any way to dynamically create import statements for each of the image links inside the JSON file for webpack to build?

I would like to avoid having to write an individual import for each image at the top of my javascript file especially if there are hundreds of items. E.g:

menu.js

import img0 from './101 cup noodles.png'
import img1 from './102 cup noodles with beef.png'
import img2 from './103 cup noodles with egg.png'
import img3 from './104 cup noodles with shrimp.png'

I have tried dynamically making the import statements with named fields and a for loop but learned that import statements need to be top level so unfortunately the following did not work:

menu.js

import data from './menu.json'

for (let i = 0; i < Object.keys(data).length; i++) {
    import ['img' + Object.keys(data)[i]] from data[i]['img'];
}

At the moment I am using the loop above to console log all of my import statements and just copy+pasting them into the top of my code but that seems extremely inelegant and I am wondering if there is a better way.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can get the properties of the object with Object.keys, then map through the array and construct the string.

const obj = {
  "0":{
      "img":"./101 cup noodles.png"
  },
  "1":{
      "img":"./102 cup noodles with beef.png"
  },
  "2":{
      "img":"./103 cup noodles with egg.png"
  },
  "3":{
      "img":"./104 cup noodles with shrimp.png"
  }
}

const res = Object.keys(obj).map(e => `import ${Object.keys(obj[e])[0] + e} from '${obj[e].img}'`).join('\n')

console.log(res)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!