【问题标题】:React Local images not loading in the page with Webpack使用 Webpack 反应本地图像未加载到页面中
【发布时间】:2020-08-11 18:37:32
【问题描述】:

我正在尝试使用 webpack 从头开始​​创建反应项目。除了图像,一切看起来都很好。似乎没有加载图像,我可以看到 src="Obeject Object"。我在下面的 webpack 上使用了相同的文件加载器和 url-loader,但没有帮助我解决这个问题。我可能遗漏了配置文件中的某些内容。

var webpack = require('webpack');
var path = require('path');
var nodeModulesPath = path.resolve(__dirname, 'node_modules');
var buildPath = path.resolve(__dirname, 'public', 'build');
var assetsPath = path.resolve(__dirname, 'src/app/assets');
var HtmlWebpackPlugin = require('html-webpack-plugin');

var config = {

    devtool: 'eval-source-map',
    devServer: {
        historyApiFallback: true
    },
    entry: {
        index: ['babel-polyfill', './src/app/index.js']
    },
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: 'index_bundle.js',
        publicPath: '/'
    },
    module: {
        rules: [
            {
                test: /\.js?$/,
                use: 'babel-loader',
                exclude: nodeModulesPath
            },

            {
                test: /\.(png|jpe?g|gif)$/i,
                loader: 'file-loader',
                options: {
                  publicPath: assetsPath,
                },
            },
            {
                test: /\.s[ac]ss$/i,
                include: [
                    nodeModulesPath,
                    path.resolve(__dirname, './src'),
                ],
                use: [
                    // Creates `style` nodes from JS strings
                    'style-loader',
                    // Translates CSS into CommonJS
                    'css-loader',
                    // Compiles Sass to CSS
                    'sass-loader',
                ],
            },
        ],
    },

    plugins: [
        new HtmlWebpackPlugin({
            template: './src/app/index.html'
        })
    ],
    devServer: {
        host: '0.0.0.0',//your ip address
        port: 3000,
        historyApiFallback: true,
        contentBase: './',
        hot: true
    },
    target: 'web'
};

module.exports = config;

我在 react 组件中使用了像下面这样的图像标签。

<img src={require('./../assets/images/logo.png')} />

【问题讨论】:

  • 如果你的应用正在被服务,你可以直接在src中给出相对路径。

标签: javascript reactjs webpack


【解决方案1】:

您是否尝试过在组件中使用您的图片,例如:

import Image from './image.jpg';

<img src={Image}/>

见:Referencing a local image in react

【讨论】:

  • 嗯,工作。理想情况下,如果假设要使用更多图像,这不是完美的解决方案..
  • 那么你要找的是动态导入(ES7):*.com/questions/35914712/…
最近更新 更多