【问题标题】:How do I fix [Object Module] in image src of webpack output?如何在 webpack 输出的图像 src 中修复 [Object Module]?
【发布时间】:2020-03-26 23:22:44
【问题描述】:

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

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

  1. 当我在条目index.html 文件中使用img 标记时,具有这样的src 属性(./imgs/image.png),dist 文件夹中的src 属性将替换为@ 987654332@。但是当我删除uri./imgs/image.png/imgs/image.png)之前的点时,dist 文件夹中的src 输出与src 的输出完全相同。这不引用我想要包含的图像。
  2. 由于 webpack 输出的src 值与源完全相同,所以我尝试粗暴地使用uri 到输出文件夹中的图像,就像/dist/img/image.png 一样。这行得通,但这不是一个很好的体验。我很想在src 文件夹中对我的图像使用uri,并让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()
  ]
};

我做了一个回购here

非常感谢您的宝贵时间

更新(02-01-2020)

评论中有人指出了问题的解决方案。 (When i using file-loader and html-loader in webpack. The src attr of image gonna be like '[object Module]')

解决方案是在file-loader规则中将esModules对象设置为false,如下所示

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

【问题讨论】:

标签: webpack webpack-html-loader


【解决方案1】:
【解决方案2】:

您可以通过 'default' 属性解决 [object module] 错误: 要求('../../images/svg-1.svg').default

【讨论】:

  • 您能详细说明一下吗?
猜你喜欢
  • 2020-03-25
  • 2020-03-23
  • 1970-01-01
  • 2021-04-13
  • 1970-01-01
  • 2019-12-31
  • 2020-08-04
  • 2017-07-03
  • 2023-01-20
相关资源
最近更新 更多