在使用asset/resource导入图片URL时,资源路径不正确
图片正在 ~/Documents/restaurant-page/dist/images/52e944639d832ccc4639.png 中生成,但在JavaScript中导入的URL是 /home/amanr/Documents/restaurant-page/distimages/52e944639d832ccc4639.png。在 dist 与 images 之间缺少一个 /。
图片在直接打开HTML文件时无法渲染,但通过webpack-dev-server提供的服务器打开时能够正确渲染。为什么会这样?如果我托管它,这会带来影响吗?
Webpack Config:
import path from 'node:path';
import HtmlWebpackPlugin from "html-webpack-plugin";
const __dirname = import.meta.dirname;
export default {
entry: "./src/index.js",
output: {
publicPath: path.resolve(__dirname, "dist/"),
filename: "index.bundle.js",
assetModuleFilename: 'images/[hash][ext][query]',
},
mode: "development",
plugins: [new HtmlWebpackPlugin({
template: path.resolve(__dirname, "src/template.html"),
filename: 'index.bundle.html'
})],
module: {
rules: [
{
test: /\.(?:js|mjs|cjs)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
targets: "defaults",
presets: [
['@babel/preset-env']
]
}
}
},
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
{
test: /\.(png|svg|jpg|jpeg|gif|webp)$/i,
type: 'asset/resource'
},
],
},
devServer: {
static: {
directory: path.resolve(__dirname, 'dist'),
},
port: 3000,
open: true,
hot: true,
compress: true,
historyApiFallback: true,
}
};
Import:
import customImg from '../images/custom.png';
export function loadHomePage() {
const heroDiv = document.createElement('div');
heroDiv.classList.add('hero', 'min-h-screen');
console.log(customImg);
heroDiv.style.backgroundImage = `url(${customImg})`;
.... }
解决方案
/home/amanr/Documents/restaurant-page/distimages/52e944639d832ccc4639.png
问题在于 - distimages
你有 publicPath 和 assetModuleFilename:
publicPath: path.resolve(__dirname, "dist/"),
assetModuleFilename: 'images/[hash][ext][query]',
Webpack通过把 publicPath 和 assetModuleFilename 拼接来解析最终的URL,因此:
path.resolve(__dirname, "dist/") => /home/amanr/Documents/restaurant-page/dist
并附加 images/...
结果是 - URL为 /home/amanr/Documents/restaurant-page/distimages/52e944639d832ccc4639.png
如何修复?
将publicPath设置为相对路径或根相对路径:publicPath: './',
然后,output 参数将变为如下:
output: {
publicPath: './',
filename: "index.bundle.js",
assetModuleFilename: 'images/[hash][ext][query]',
path: path.resolve(__dirname, "dist"),
clean: true, // this cleans the dist folder before each build
},
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。