Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs require image url in variable is not working

Strange problem

I'm dynamically including the path to an image in the source directory.

Putting the image directory in as a string works Fine (the part I commented out), but as soon as I put it in a variable it gives me the error " Cannot find module ".""

   var imageDir="assets/img/MyImage.png";
  --Working     // const imageData= require('assets/img/MyImage.png');
  --Not Working    const imageData= require(imageDir);

Any one know why?

Same-ish problem Here No answer unfortunately

like image 409
Ruan Avatar asked Nov 14 '25 17:11

Ruan


1 Answers

Webpack needs to know what files to bundle during compile-time, but the real path value for expression(variable) only be given in runtime, you need require.context:

/* If the structure is like:

    src -
         |
          -- index.js (where these codes are deployed)
         |
          -- assets - 
                     |
                      --img
*/  

      
let assetsPath = require.context('./assets/img', false, /\.(png|jpe?g|svg)$/); 

// See where are the images after bundling.
// console.log(assetsPath('./MyImage.png'));

// You can put all the images you want in './assets/img', and access it. 
var newElement = {
    "id": doc.id,
    "background": assetsPath('./MyImage.png');
};
like image 84
Carr Avatar answered Nov 17 '25 08:11

Carr