React/Webpack 图像无法加载,但 CSS 可以加载

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

所以我只想在我的 React 应用程序中使用一些图像,但图像没有加载。有些图像是这样在 CSS 中设置的:

background-image: url('/../img/logo.png'); 

我想在 React 组件内部使用图像的另一种方式 img 标签,我该怎么做?

这是我的 webpack 配置:

const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = (env) => {
  const isProduction = env === 'production';
  return {
    entry: './src/app.js',
    output: {
      path: path.resolve(__dirname, 'public', 'dist'),
      filename: 'bundle.js'
    },
    module: {
      rules: [{
        loader: 'babel-loader',
        test: /\.js$/,
        exclude: /node_modules/
      }, {
        test: /\.s?css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              // you can specify a publicPath here
              // by default it use publicPath in webpackOptions.output
              publicPath: '../'
            }
          },
          {
            loader: 'css-loader',
            options: {
              sourceMap: true
            }
          },
          {
            loader: 'sass-loader',
            options: {
              sourceMap: true
            }
          }
        ]
      }]
    },
    plugins: [
      new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: "styles.css",
    })
    ],
    devtool: isProduction ? 'source-map' : 'inline-source-map',
    devServer: {
      contentBase: path.resolve(__dirname, 'public'),
      historyApiFallback: true,
      publicPath: '/dist/'
    },
    performance: {
      hints: process.env.NODE_ENV === 'production' ? "warning" : false
    },
  }
};

公共文件夹内的index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Kinnisvara ABC</title>
    <link rel="stylesheet" href="/dist/styles.css" type="text/css">
  </head>
  <body>
    <div id="app"></div>
    <script src="/dist/bundle.js"></script>
  </body>
</html>

CSS 正在加载,但图像尚未加载。

我的文件结构图片: enter image description here

enter image description here

enter image description here

有人可以帮我吗?

html css reactjs webpack
4个回答
1
投票

有2种方式

  1. 使用 webpack url-loader 将此行添加到 webpack 文件中的规则模块

    { 测试:/.(png|jpg|woff|woff2|eot|ttf|svg|gif)$/,加载器:'url-loader?limit=1024000' }

  2. 使用服务来指向图像


1
投票
    {
      test: /\.(gif|png)$/, //Customise according to your need
      use: [
        {
          loader: 'url-loader',
          options: {
            limit: 10000,
            name: PATH + '.[ext]' //Path will be assets or image path
          }
        }
     ]
    }
像这样在 webpack 配置中

配置 url-loader


0
投票

您没有添加像 css 这样的图像加载器,所以尝试添加它

test: /\.(gif|jpe?g|png)$/,

0
投票

解决了这个问题:

{ 加载器:'url-加载器', 选项: { 限制:10000, 名称: '[名称].[扩展名]', es模块:假 }, },

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.