I have a folder that contains image files in different formats. I want to dynamically import all these files and display them in a component/use them later. How can I do this?
-
Does this answer your question? [Typescript 1.8 modules: import all files from folder](https://stackoverflow.com/questions/38158429/typescript-1-8-modules-import-all-files-from-folder) – about14sheep Apr 02 '23 at 00:17
-
I have working solution and already posted the answer. I only wanted to share my approach because I didn't find a working solution for Typescript here. – Sebi Apr 02 '23 at 00:19
1 Answers
I wrote this importAll function to dynamically import all image files in a folder.
export const importAll = <T>(
requireContext: __WebpackModuleApi.RequireContext
) => {
const importedPictures: { default: T }[] = requireContext
.keys()
.filter((key) => key.match(/\.\//))
.map(requireContext) as { default: T }[]
return importedPictures.map((el) => el.default)
}
To use this function, you first need to install the @types/webpack-env
package as a dev dependency. This package provides type definitions for Webpack's require.context function, which is used by the importAll function.
Next, you need to use Webpack's require.context function to get a reference to the folder containing your image files.
const images = importAll<HTMLImageElement>(
require.context('./IMAGE_FOLDER', false, /\.(png|jpe?g|svg)$/)
)
In this example, ./IMAGE_FOLDER is the path to the folder containing your image files, and /.(png|jpe?g|svg)$/ is a regular expression that matches files with the .png, .jpg, .jpeg, or .svg extension. You can modify this regular expression to match the extensions of the image files in your folder.
Once you have the images array, you can use it to render your images in your component. Here's an example with React of how you can render the images using the map function:
import React from 'react'
const images = importAll<HTMLImageElement>(
require.context('./IMAGE_FOLDER', false, /\.(png|jpe?g|svg)$/)
)
const ImageGallery = () => {
return (
<div>
{images.map((image, index) => (
<img key={index} src={image.src} alt={`Image ${index}`} />
))}
</div>
)
}
export default ImageGallery

- 398
- 3
- 10