Search code examples
typescriptwebpackimportts-loaderimageloader

webpack import files dynamically while build


I have webpack + typescript project that has about 1000 images. I also have a file that describes this images like this:

[{
  code: 'imageACode',
  alt: 'imageAAlt',
  source: './pathToA.jpg'
}]

Same code for B,C,D and other 997 images I got. At the end of the day on client side that should generate html below:

<img src="/static/pathToA.jpg" alt="imageAAlt"/>

And I also use imageACode to replace some html code to that image (whatever).

Ok the simplest way I can do this is:

import a from "../assets/images/pathToA.jpg"

{
  code: 'imageACode',
  alt: 'imageAAlt',
  source: a
}

Is there more elegant way like so:

{
  code: 'imageACode',
  alt: 'imageAAlt',
  source: import '../assets/images/pathToA.jpg'
}

Or probably some kind of forEach that webpack should run.


Solution

  • If you have a lot of assets and you don't want to manually import them, you can use require.context.

    This is the simple example that might work in your case:

    const images = require.context('../assets/images/', false, /\.jpg$/)
    const descriptions = images.keys().map(images).map(source => ({
        code: 'code',
        alt: 'alt',
        source
    })