【问题标题】:404 when fetching image with webpack使用 webpack 获取图像时出现 404
【发布时间】:2023-03-14 13:05:02
【问题描述】:

我正在点击此链接将图像添加到我的捆绑包中:

https://webpack.js.org/guides/asset-management/

我的根文件夹中有以下文件结构:

index.html

index.js

图像文件夹(带有 svg)

这是我的 webpack.config.js

// Generated using webpack-cli https://github.com/webpack/webpack-cli

const path = require('path');

const isProduction = process.env.NODE_ENV === 'production';
const HtmlWebpackPlugin = require("html-webpack-plugin");

const stylesHandler = 'style-loader';



const config = {
    entry: './index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'index_bundle.js'
    },
    devServer: {
        open: true,
        historyApiFallback: true,
        host: 'localhost'
    },
    plugins: [
        new HtmlWebpackPlugin({
            title: 'Custom template',
            // Load a custom template (lodash by default)
            template: 'index.html'
        })
    ],
    module: {
        rules: [
            {
                test: /\.(png|svg|jpg|jpeg|gif)$/i,
                type: 'images',
            },
        ]
    }
};


module.exports = () => {
    if (isProduction) {
        config.mode = "production";
    } else {
        config.mode = "development";
    }
    return config;
};

我正在使用以下 webpack 模块:

    "webpack": "^5.64.4",
    "webpack-cli": "^4.9.1",
    "webpack-dev-server": "^4.6.0",
    "wepack-cli": "0.0.1-security"

在我的 js 文件中,我试图通过以下方式将图像添加到 SVG 元素:

.attr('xlink:href', 'images/virtual-machine.svg')

但我得到 404。

【问题讨论】:

  • 字符串文字路径 'images/virtual-machine.svg' 不会正常工作。您需要通过importrequire 导入资产
  • @JózefPodlecki - 我可能遗漏了一些信息,但是在查看 localhost:8080/webpack-dev-server 时,我没有看到任何图像文件夹,所以如果我通过代码使用 require,我认为它也会失败。
  • 现在我不确定type: 'images' 是否会起作用。你使用的是什么 webpack 版本?在 webpack 5 中有 type: 'asset/resource' 只有在你直接在代码中导入它时才会起作用
  • @JózefPodlecki - 用 webpack 包更新了我的帖子

标签: webpack webpack-dev-server webpack-file-loader


【解决方案1】:

尝试使用resource资产模块

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

现在 webpack 必须知道你正在使用这个图像。导入后应该可以工作。

确保路径正确,因为它会从当前文件夹中查找路径

import virtualMachineSvg from 'images/virtual-machine.svg'

.attr('xlink:href', virtualMachineSvg)

require

const virtualMachineSvg = require('images/virtual-machine.svg');

.attr('xlink:href', virtualMachineSvg)

【讨论】:

  • 太棒了——它有效!
猜你喜欢
  • 2014-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-30
  • 2019-01-25
  • 1970-01-01
  • 2013-08-18
  • 1970-01-01
相关资源
最近更新 更多