Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading images dynamically with Parceljs

Tags:

parceljs

Is it possible to load images dynamically with parceljs bundler, when image names are not known at build time

Is there something similar to webpack's require.context in parcel

Code Snippet (using React and Parcel) This works fine

...
<img src={require('../images/Image4.jpg')}/>
...

But if expression is used, it throws "Uncaught Error: Cannot find module"

...
var imgName = "Image4";
...
...
<img src={require('../images/' + imgName + '.jpg')}/>
...

Image - Uncaught Error: Cannot find module

So, am i doing this wrong? is there any other way to do this with parcel

like image 217
Shashank Vinayak Avatar asked Jan 21 '18 10:01

Shashank Vinayak


2 Answers

Based on Luke Robertson answer tried the similar hack and it worked for me:

import images from '../assets/cover/images/*.jpg';
const file_name = "file-name"
<img src=`${images[file_name]}` />
like image 109
Glance Avatar answered Sep 28 '22 03:09

Glance


I dont think this is currently possible, one hacky way iv got it around it, is to do this :

import icons from './assets/icons/**'

const icon_file_name = 'user'
const specificIcon = icons[`${icon_file_name}.png`]

<img src={specificIcon} />
like image 37
Luke Robertson Avatar answered Sep 28 '22 03:09

Luke Robertson