通过webpack处理后,图像不会显示

问题描述 投票:0回答:1

我开始在我的React应用程序中使用webpack来捆绑图像,但它们没有显示在浏览器中(有一个<img/>标签,但没有图像)。如果我运行“webpack”图像存在于具有散列名称的公共文件夹中,并且如果我运行“webpack-dev-server”,它还会显示图像被捆绑,但浏览器中仍然没有。这是我的webpack配置文件:

module.exports = (env) => {
const isProduction = env === 'production';
const CSSExtract = new ExtractTextPlugin('styles.css');

return {
    entry: ['babel-polyfill', './src/app.js'],
    output: {
        path: path.resolve(__dirname, './public/scripts'),
        filename: 'bundle.js'
    },
    module: {
            rules: [{
                 loader: 'babel-loader',
                 test: /\.js$/,
                 exclude: /node_modules/
            },
            {
                test: /\.(png|jp(e*)g|svg)$/,
                use: [{
                    loader: 'url-loader',
                    options: {
                        limit: 8000, // Convert images < 8kb to base64 strings
                        name: 'images/[hash]-[name].[ext]'
                    }
                }]
            },
            {
            test: /\.s?css$/,
            use: CSSExtract.extract({
                use : [
                    {
                        loader : 'css-loader',
                        options : {
                            sourceMap : true // source map for css in development
                        }
                    },
                    {
                        loader : 'sass-loader',
                        options : {
                            sourceMap : true
                        }
                    },
                    {
                        loader: "jshint-loader"
                    }
                ]
            })

        },
        ]
    },
    plugins : [
        CSSExtract,
    ],
    devtool: isProduction ? 'source-map' : 'cheap-eval-source-map', // source map for locating a bug in source files, not in the bundle
    devServer: {
        contentBase: path.join(__dirname, "public"),
        publicPath: "/scripts/",
        historyApiFallback: true // this line is for client-side routing
    },
}

}

这就是我将图像添加到我的应用程序的方式:

import img1 from '../../assets/img/ticket.jpg';

这就是我在render()方法中使用它的方法。

<img src={img1}/>

我在浏览器devtools中看到了这一点,但图像本身并没有出现:

<img src="images/9011429377e91d003e5b64251ac3b9a8-ticket.jpg">

如何修复它并使图像显示?

webpack webpack-file-loader
1个回答
0
投票

嗨,我不知道这是否有帮助。当我导入图像时,我会做一些不同的事情并使用图像的名称而不是使用生成的数字。

在我提出的应用程序脚本中。

import '../../assets/img/ticket.jpg';

然后在我放的渲染方法中。

 // notice the slash as the front of the "src"
 <img src="/assets/ticket.jpg">

在我的webpack中我有这个:

  {
    test: /\.(png|jpg|gif|json|xml|ico|svg)$/,
    use: [
      {
        loader: 'file-loader',
        options: {
          name: '[name].[ext]',
          outputPath: 'assets/',
          publicPath: '/'
        }
      }
    ]
  }
© www.soinside.com 2019 - 2024. All rights reserved.