使用react和webpack 4加载本地映像

时间:2018-03-21 15:05:08

标签: javascript node.js reactjs

我正在构建一个react应用程序,它使用node和express从服务器呈现JSON数据。我面对本地图像的问题将无法加载。 的 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> app>客户端>图片文件夹中,且代码位于客户端文件夹中。

该应用程序从JSON呈现组件网格。每个网格都是一个listComponent,它有一个复选框,一个带有title和desc的图像。

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.log('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-react-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

1 个答案:

答案 0 :(得分:-1)

您需要将url loader添加为webpack.config.js文件中的一个模块。

module: {
  loaders: [
    {
      test: /\.(png|jpg)$/,
      loader: 'url?limit=25000'
    }
  ]
}