Javascript 网页包文件加载程序未加载图像,404错误

Javascript 网页包文件加载程序未加载图像,404错误,javascript,reactjs,spring-boot,webpack,webpack-file-loader,Javascript,Reactjs,Spring Boot,Webpack,Webpack File Loader,我正在开发一个SpringBoot/React项目,它也使用webpack。我只是尝试渲染存储在项目本地的图像。我一直在尝试使用npm的文件加载器,但没有用。每当我运行应用程序时,我试图加载的图像都会出现404错误 我也尝试过使用url加载器和图像网页包加载器,但两者都会导致404错误 webpack.config.js const path = require('path'); module.exports = { entry: './src/main/js/index.js', d

我正在开发一个SpringBoot/React项目,它也使用webpack。我只是尝试渲染存储在项目本地的图像。我一直在尝试使用npm的文件加载器,但没有用。每当我运行应用程序时,我试图加载的图像都会出现404错误

我也尝试过使用url加载器和图像网页包加载器,但两者都会导致404错误

webpack.config.js

const path = require('path');

module.exports = {
  entry: './src/main/js/index.js',
  devtool: 'sourcemaps',
  cache: true,
  debug: true,
  output: {
    path: __dirname,
    filename: './src/main/resources/static/built/bundle.js',
  },
  module: {
    loaders: [
      {
        test: path.join(__dirname, '.'),
        exclude: /(node_modules)/,
        loader: 'babel',
        query: {
          cacheDirectory: true,
          presets: ['es2015', 'react'],
        },
      },
      {
        test: /\.css$/,
        loaders: ['style-loader', 'css-loader'],
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        loader: 'file-loader',
      },
    ],
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: ['babel-loader', 'eslint-loader'],
      },
      {
        test: /\.(png|jpe?g|gif)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'img/[hash]-[name].[ext]',
            },
          },
        ],
      },
    ],
  },
};

header.js

import './css/header-style.css';
import React from 'react';
import Logout from './Logout';
import { Link } from 'react-router-dom';

import logo from './img/Logo.png'; // The image I'm trying to load.

/**
 * Renders Logo, header navigation links to other pages, and the logout component.
 */
function Header() {
  return (
    <div className="row wrapper-header">
      <nav className="navbar navbar-expand-lg">
        <a className="navbar-brand" href="#">
          <img className="logo-width" alt="Logo" src={logo} />
        ...

当我运行webpack时,我可以看到它会发出带有它给出的散列的png,例如:在根项目文件夹目录F5C281D45D55B24ED52C9FEE307F36E.png中,我猜你的HTML页面是指
/build/bundle.js
,相对于Spring静态资源目录的React应用程序路径。 Webpack将图像文件输出到与
bundle.js
相同的位置(
…../static/build/imagehash.png
),并使用您所说的散列。当React应用程序引用图像时,它将使用一个相对路径,如
imagehash.png
,假设它位于同一目录中。但当Spring看到该路径时,它将查找
static/imagehash.png
(以及其他静态资源位置)。它不知道如何查看
静态/build/
目录

您可以使用
publicPath
选项告知文件加载器从web服务器上的何处引用图像。像这样:

        {
            test: /\.(png|svg|jpg|gif)$/,
            loader: 'file-loader',
            options: {
                publicPath: 'built'
            }
        }
        {
            test: /\.(png|svg|jpg|gif)$/,
            loader: 'file-loader',
            options: {
                publicPath: 'built'
            }
        }