首页 > 解决方案 > Webpack 5 如何在 HTML 文件中显示图像

问题描述

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 ......

有人可以帮我吗?

标签: webpackwebpack-file-loaderwebpack-5

解决方案


您需要更改旧资产加载器...对于图像,建议使用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 资产加载器指南中查看更多详细信息


推荐阅读