【问题标题】:Loading local images using react and webpack 4使用 react 和 webpack 4 加载本地图像
【发布时间】:2018-08-30 18:43:17
【问题描述】:

我正在构建一个反应应用程序,它使用节点和 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>client>images文件夹中,代码在client文件夹中。

应用程序从 JSON 呈现组件网格。每个网格都是一个列表组件,它有一个复选框、一个带有标题和描述的图像。

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

【问题讨论】:

    标签: javascript node.js reactjs


    【解决方案1】:

    您需要在 webpack.config.js 文件中添加 url 加载器作为您的模块之一。

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

    【讨论】:

    • 我编辑了该部分并安装了 'url-loader' 但仍然显示与上述相同的错误
    猜你喜欢
    • 1970-01-01
    • 2017-08-31
    • 2018-12-26
    • 2017-06-06
    • 2017-01-18
    • 2019-02-28
    • 2018-12-09
    • 2018-12-28
    • 2018-12-13
    相关资源
    最近更新 更多