4

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

2
  • 1
    Can you give a little more information on how you are using the object when you say "working" and "not working"? Is background being passed to an img element, or is the object used to set CSS with a style property? It could be any number of things from string type conversion to when require gets called and the variable collected. Commented Mar 4, 2018 at 15:56
  • @JessB Hi Jess, The problem seems to be before it I use my "newelement" object. The problem seems to be the require() method on a variable with a string as appose to just having the string in the require method. I've updated an example of where it fails Commented Mar 4, 2018 at 16:25

2 Answers 2

6

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');
};
Sign up to request clarification or add additional context in comments.

1 Comment

This is perfect!
0

If you wish use image on your react web application you can use next code

when use directly in html tag, but if you can use in part of java script, you must use const image = require('../Assets/image/03.jpg') and call letter this constant like this {image} between example tags

2 Comments

This is not dynamic
Yes, but if you wish dynamic you must use setState and make some json data file, and connect this with event onClick. In any case best away is require('../Assets/image/03.jpg') because this is safety away for find picture on your web page.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.