Reactjs 要求变量中的图像 url 不起作用
Reactjs require image url in variable is not working
奇怪的问题
我在源目录中动态包含图像的路径。
将图像目录作为字符串放入工作正常(我注释掉的部分),但是一旦我将它放入变量中,它就会给我错误“找不到模块”。""
var imageDir="assets/img/MyImage.png";
--Working // const imageData= require('assets/img/MyImage.png');
--Not Working const imageData= require(imageDir);
有人知道为什么吗?
同样的问题Here
很遗憾没有答案
如果您希望在您的 React Web 应用程序中使用图像,您可以使用下一个代码
当直接在 html 标签中使用时,但如果您可以在 java 脚本的一部分中使用,则必须使用 const image = require('../Assets/image/03.jpg')
并在示例标签之间像这样 {image}
调用字母常量
Webpack 需要知道在 compile-time 期间要打包哪些文件,但是表达式(变量)的真实路径值只在运行时给出,你需要 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');
};
奇怪的问题
我在源目录中动态包含图像的路径。
将图像目录作为字符串放入工作正常(我注释掉的部分),但是一旦我将它放入变量中,它就会给我错误“找不到模块”。""
var imageDir="assets/img/MyImage.png";
--Working // const imageData= require('assets/img/MyImage.png');
--Not Working const imageData= require(imageDir);
有人知道为什么吗?
同样的问题Here 很遗憾没有答案
如果您希望在您的 React Web 应用程序中使用图像,您可以使用下一个代码
当直接在 html 标签中使用时,但如果您可以在 java 脚本的一部分中使用,则必须使用 const image = require('../Assets/image/03.jpg')
并在示例标签之间像这样 {image}
调用字母常量
Webpack 需要知道在 compile-time 期间要打包哪些文件,但是表达式(变量)的真实路径值只在运行时给出,你需要 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');
};