我正在點擊此鏈接將影像添加到我的包中:
https://webpack.js.org/guides/asset-management/
我的根檔案夾中有以下檔案結構:
索引.html
索引.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。
uj5u.com熱心網友回復:
嘗試使用資源資產模塊
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/377429.html
標籤:网络包 webpack-dev-server webpack-文件加载器
