首页 > 解决方案 > 如何修复 webpack 输出的图像 src 中的 [Object Module]?

问题描述

我正在尝试使用 Webpack 设置一个现代的香草网络启动器。

webpack-html-loader添加and时我卡住了html-loader。这就是发生的事情......

  1. 当我使用条目文件中的img标签时,具有这样的属性 ( ),文件夹中的属性被替换为. 但是当我删除( to )之前的点时,文件夹中的输出与. 这不引用我想要包含的图像。index.htmlsrc./imgs/image.pngsrcdist[object Module]uri./imgs/image.png/imgs/image.pngsrcdistsrc
  2. 由于srcwebpack 输出的值与源完全相同,所以我尽量粗略地使用uri输出文件夹中的图像,如下所示/dist/img/image.png。这行得通,但这不是一个很好的体验。我很想uri在文件夹中使用我的图像,并在构建时src让 webpack 替换它。dist这可能吗?

这是我的文件结构之后的样子npm run build

- dist
  - imgs
    - image.png
  - index.html
  - main.js
- node_modules
- src
  - index.html
  - imgs
    - image.png
- package.json
- package-lock.json
- webpack.config.js

这是我的webpack.config.js

const HTMLWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const path = require("path");

module.exports = {
  module: {
    rules: [
      {
        test: /\.(html)$/,
        use: [
          {
            loader: "html-loader",
            options: {
              minimize: false
            }
          }
        ]
      },
      {
        test: /\.(png|jpe?g)$/,
        use: [
          {
            loader: "file-loader",
            options: {
              outputPath: "imgs",
              publicPath: "imgs",
              name: "[name].[ext]"
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new HTMLWebpackPlugin({
      template: path.resolve(__dirname, "src/index.html")
    }),
    new CleanWebpackPlugin()
  ]
};

我在这里做了一个回购

非常感谢您的时间

更新(02-01-2020)

评论中有人指出了问题的解决方案。(当我在 webpack 中使用 file-loader 和 html-loader 时。图像的 src 属性会像 '[object Module]'

解决方案是像这样在规则中设置esModules对象falsefile-loader

{
  test: /\.(png|jpe?g)$/,
  use: [
    {
      loader: "file-loader",
      options: {
        // Here!!!
        esModule: false,
        outputPath: "images",
        publicPath: "images",
        name: "[name].[ext]"
      }
    }
  ]
}

标签: webpackwebpack-html-loader

解决方案



推荐阅读