Webpack 5 如何在 HTML 文件中显示图像

Webpack 5 How to display images in HTML file

我将 webpack 用于一个小型应用程序,到目前为止它运行良好,除了我在显示图像时遇到问题 - 我收到 404。

这是我的 webpack 配置:

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

module.exports = {
   entry: {
     index: './src/index.js'
   },
   output: {
     path: path.resolve(__dirname, 'dist'),
     filename: '[name].js'
   },
   module: {
    rules: [
        {
            test: /\.(sa|sc|c)ss$/,
            use: [
            MiniCssExtractPlugin.loader,
              { loader: 'css-loader', options: { importLoaders: 2, sourceMap: true } },
              { loader: 'postcss-loader', options: { sourceMap: true } },
              { loader: 'sass-loader', options: { implementation: require('sass'), sourceMap: true } },
            ]
        },
        {
            test: /\.(png|jpg|gif|svg|eot|ttf|woff)$/,
            use: [
              {
                loader: 'file-loader',
                options: {
                  name: '[name].[ext]',
                  outputPath: 'src/assets/images'
                }
              },
            ],
        },
        {
            test: /\.js$/i,
            use: {
              loader: 'babel-loader',
              options: {
                presets: ['@babel/preset-env'],
              },
            },
        },
        {
            // Extract any CSS content and minimize
            test: /\.css$/,
            use: [
                MiniCssExtractPlugin.loader,
                { loader: 'css-loader', options: { importLoaders: 1 } },
                { loader: 'postcss-loader' }
            ]
        }  
      ]
   },
   plugins: [
      new HtmlWebpackPlugin({
        template: './dist/index.html',
        inject: 'body',
        chunks: ['index'],
        filename: 'index.html'
      }),
      new MiniCssExtractPlugin({
        filename: 'src/css/[name].min.css'
     }),
  ],
  devServer: {
    watchContentBase: true,
    contentBase: path.resolve(__dirname, 'dist'),
    open: true
  }
};

然后在我的 index.html 中,我尝试这样做:

<img class="object-cover z-0 w-full h-full" src='/src/assets/images/top_image.png'>

但就像我之前提到的,我得到 404...

有人可以帮我吗?

您需要更改旧资产加载器...对于图像,建议使用 asset/resource

使用 asset/resource 代替 file-loader。 类似于:

编辑您的规则:

{
   test: /\.(png|jpg|gif|svg|eot|ttf|woff)$/,
   type: 'asset/resource'
}

并在您的 webpack.output 中添加:

output: {
 path: path.resolve(__dirname, 'dist'),
 filename: '[name].js',
 assetModuleFilename: 'src/assets/images/[name].[ext]'
}

您可以在 Webpack assets loader guide

上查看更多详细信息