webpack 5 图像未使用“reactjs”加载

3gw*_*ain 0 reactjs webpack

这是我的 webpack.config:

const HtmlPlugin = require("html-webpack-plugin");
const path = require("path");
module.exports = {
    watch: true,
    output:{
        path:path.resolve(__dirname, "build"),
        filename:"bundle.js"
    },
    module:{
        rules:[
            {
                test:/\.(js|jsx)$/,
                exclude:/node_modules/,
                use:[{loader:"babel-loader"}]
            },
            {
                test:/\.html$/,
                use:[{loader:"html-loader"}]
            },
            {
                test: /\.(png|jpe?g|gif)$/i,
                use: [{loader: 'file-loader'}],
            }
        ]
    },
    plugins:[
        new HtmlPlugin({
            filename:"index.html",
            template:"./src/index.html"
        })
    ],
    devtool: 'inline-source-map',
    devServer:{
        historyApiFallback:true,
        port:5000
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在 index.js 中导入图像:

import React from "react";
import ReactDOM from "react-dom";
import Img from "./images/flower.jpg"; 

const App = () => {
    return (
        <div>
            <h1>Hello World!!</h1>
            <img src="{Img}" />
        </div>
    )
};

ReactDOM.render(<App />, document.getElementById("root"));
Run Code Online (Sandbox Code Playgroud)

但是当我启动应用程序时,没有加载图像。看起来像:

没有加载图像

并收到一些令人不安的消息,例如:

"webpack performance recommendations: You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application. For more info visit https://webpack.js.org/guides/code-splitting/"

怎么解决这个问题?我用 "webpack": "^5.11.0", "webpack-cli": "^4.2.0",

提前致谢。

ske*_*s88 5

Webpack 5 文档声明您可以使用内置的资产模块,因此您不需要file-loader: https: //webpack.js.org/guides/asset-management/#loading-images

在 webpack 配置文件中,将图像处理规则更改为:

      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
      },
Run Code Online (Sandbox Code Playgroud)

在 中index.js,更改<img src="{Img}" /><img src={Img} />(如 Magofoco 建议的那样)。