【发布时间】: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' 不会正常工作。您需要通过
import或require导入资产 -
@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