Webpack 5 将不会加载动画 gif 文件

问题描述 投票:0回答:2

我是 webpack 新手,但遵循官方文档:https://webpack.js.org/guides/asset-management/#setup

我正在尝试使用 webpack 5 加载动画 gif。

gif 的占位符正在加载,但控制台错误是: “获取文件:///home/jordan/repos/KrabbShack/dist/[object%20HTMLParagraphElement] net::ERR_FILE_NOT_FOUND [对象%20HTMLParagraphElement]:1“

当我运行构建时,出现此错误: ./src/assets/krabbyPatty.gif 中的错误 1:6 模块解析失败:意外字符“�”(1:6) 您可能需要适当的加载程序来处理此文件类型,目前没有配置加载程序来处理此文件。

我的gif文件路径 src/assets/krabbyPatty.gif

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist'),
  },
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
        template: path.resolve(__dirname, './src/template.html')
    })
  ]
};

我正在 home.js 路径中工作的模块:./src/home.js

import KrabbyPatty from './assets/krabbyPatty.gif';
function createContent() {
    const newDiv = document.createElement('div');
    const slogan = document.createElement('p');
    newDiv.classList.add('content')
    slogan.textContent = 'Home of the beloved Krabby Patty';
    const patty = new Image(325, 325)
    patty.src = {KrabbyPatty}
    newDiv.appendChild(slogan);
    newDiv.appendChild(patty);

    return newDiv;
}

我也尝试过:

    const patty = document.createElement('img');
    patty.src = krabbyPatty;

我尝试过不像官方文档那样用大括号和括号括起来。我尝试只使用 img 文字并将 html 写在反引号内,但我可能做错了,我更愿意了解为什么官方文档方法是不为我工作。

附注这是我的第一个问题,如果我的格式错误,请原谅我,我愿意接受建设性的批评。我搜索了与此相关的其他问题,但我发现的只是 webpack 5 之前的方法,其中包含 url-loader 等解决方案,但该解决方案也失败了,并且根据我的阅读,webpack 5 不需要。

javascript html dom gif webpack-5
2个回答
0
投票

我找到的解决方案是在 webpack.config.js 文件中,在模块规则中添加一个生成器:

{
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
        generator: {
          filename: 'images/[name][ext]'
       }
      },

0
投票

您找到解决方案了吗?

© www.soinside.com 2019 - 2024. All rights reserved.