Я создаю приложение для реагирования, которое отображает данные JSON с сервера с помощью node и express. Проблема, с которой я сталкиваюсь, локальные изображения не загружаются. JSON
{
"items":[
{
"_id": 1,
"isActive": true,
"image": "../images/pic1.jpg",
"imageTitle":"Picture 1",
"imageDesc": "Nisi cupidatat nulla culpa ullamco id reprehenderit laborum pariatur non reprehenderit ipsum nostrud magna nisi. Eu exercitation id adipisicing ad aute quis adipisicing quis sit eiusmod ut commodo quis. Enim magna labore cupidatat laborum reprehenderit ipsum ullamco excepteur nisi occaecat officia ipsum.\r\n"
}]
}
Все изображения находятся в папке SRC> приложение> клиент> изображения, а коды - в папке клиента.
Приложение отображает сетку компонентов из JSON. Каждая сетка представляет собой listComponent, в котором есть флажок, изображение с заголовком и описание.
listComponent.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import CheckBox from '../common/checkbox';
import ImageComponent from '../common/image';
class ListComponent extends React.Component{
constructor(props){
super(props);
this.handleArray = this.handleArray.bind(this);
}
handleArray(){
console.info('List component props',this.props);
return this.props.items.map((val) =>
<div className = "col" key = {val._id} >
<header>
<CheckBox isSelected = {val.isActive}/>
</header>
<section>
<ImageComponent image = {val.image} imageTitle = {val.imageTitle} imageDesc = {val.imageDesc} />
</section>
<footer>
<i class = "fa fa-image-icon"></i>
<i class = "fa fa-info-circle"></i>
</footer>
</div>
);
}
render(){
return(
<div class = "flex-Container">
{this.handleArray()}
</div>
);
}
}
export default ListComponent;
Я могу получить точные данные JSON и отобразить все компоненты, кроме изображения.
ImageComponent.js
class ImageComponent extends Component {
render() {
const selectedImg = this.props.image;//
return (
<figure>
<img src = { require('selectedImg') } width ='100' height ='100' alt='test'/>
<figcaption>{this.props.imageTitle}</figcaption>
<div>{this.props.imageDesc}</div>
</figure>
);
}
}
export default ImageComponent;
Я просмотрел много ответов в stackoverflow, но все еще не работал. Я заметил одну вещь, если в ImageComponent:
<img src = { require('../images/pic1.jpg') } width ='100' height ='100' alt='test'/>
Я указываю относительный путь (точный путь, как в данных JSON), он извлекает изображение, но при извлечении данных с помощью сервера оно не отображается.
Ошибка:
ERROR in ./src/app/client/common/image.js
Module not found: Error: Can't resolve '../images/pic1.png' in 'D:\Sucheta\react-redux-json-with-webpack\src\app\client\common'
@ ./src/app/client/common/image.js 13:11-40
@ ./src/app/client/components/listComponent.js
@ ./src/app/client/containers/App.js
@ ./src/app/index.js
Примечание: я не использую приложение create-response-app webpack.config.js
const path = require('path');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const DIST_DIR = path.resolve(__dirname, 'public');
const SRC_DIR = path.resolve(__dirname, 'src');
const BrowserSyncPluginConfig = new BrowserSyncPlugin({
host: 'localhost',
port: 3000,
proxy: 'http://localhost:8080/',
reload: false
});
const HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
template: './src/app/index.html',
filename: 'index.html'
});
const config = {
mode: 'development',
entry: SRC_DIR + '/app/',
output: {
path: DIST_DIR,
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [{ loader: 'babel-loader' }]
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
options: {
//minimize: true
}
}
]
},
{
test: /\.css$/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
minimize: true
}
}
]
},
{
test: /\.(png|jpg|gif)$/,
use: [
{ loader: 'file-loader',
options: {
outputPath: 'assets/'
}
}
]
}
]
},
resolve: {
extensions: ['.js', '.jsx', 'css']
},
devServer: {
contentBase: path.join(DIST_DIR)
},
plugins: [
BrowserSyncPluginConfig,
HTMLWebpackPluginConfig
]
};
module.exports = config;
Структура папок:
--node_modules
--src
--app
--client
-common
-checkbox.js
-image.js
-components
-listComponent.js
-containers
-App.js
-css
-images
-pic1.jpg
--server
-server.js
-data.json
-index.html
-index.js



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


вам нужно добавить загрузчик URL-адресов в качестве одного из ваших модулей в файл webpack.config.js.
module: {
loaders: [
{
test: /\.(png|jpg)$/,
loader: 'url?limit=25000'
}
]
}
Я отредактировал эту часть и установил url-loader, но по-прежнему показывает ту же ошибку, что и выше.