Reactjs require image url in variable is not worki

2019-07-15 06:20发布

问题:

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

回答1:

Webpack needs to know what files to bundle at compile time, but expression only be given value in runtime, you need require.context:

/* If structure like:

    src -
         |
          -- index.js (where these code deploy)
         |
          -- assets - 
                     |
                      --img
*/  


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

// See where is the image after bundling.
// console.log(assetsPath('./MyImage.png'));
// In fact you could put all the images you want in './assets/img', and access it by index: './otherImg.jpg' 
var newelement = {
    "id": doc.id,
    "background": assetsPath('./MyImage.png');
};


回答2:

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