React.js要求变量中的图像URL不起作用 [英] Reactjs require image url in variable is not working

查看:142
本文介绍了React.js要求变量中的图像URL不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

奇怪的问题

我正在动态地在源目录中包含图像的路径.

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);

有人知道为什么吗?

同样的问题这里 不幸的是,没有答案

Same-ish problem Here No answer unfortunately

推荐答案

Webpack需要知道在编译时要捆绑的文件,但是仅在运行时给表达式赋值,您需要

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');
};

这篇关于React.js要求变量中的图像URL不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆