You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Webpack5使用handlebars-loader时Asset modules不输出图片到dist,如何解决?

问题原因

handlebars-loader仅负责将.hbs模板编译为HTML字符串,不会自动解析字符串内的图片等静态资源路径,因此Webpack5的Asset Modules无法识别到这些资源,不会打包输出到dist目录,无需使用html-loader的preprocessor复杂配置,直接调整loader链式调用即可解决。

配置修改方案

  1. 调整.hbs文件的loader规则,追加html-loader处理编译后的HTML内的资源路径(loader执行顺序为从右到左,因此html-loader写在数组前侧,会在handlebars编译完成后执行资源解析)
{
  test: /\.hbs$/i,
  use: ['html-loader', 'handlebars-loader'],
}
  1. 可选适配调整:如果开发环境访问图片出现404,可将output.publicPath修改为'/',生产环境再按需替换为对应静态资源CDN路径。

动态图片适配说明

如果你的hbs模板中使用Handlebars插值动态传入图片路径,需要在JS入口中提前引入图片资源再传入模板参数,示例如下:

// index.js 入口文件
import logo from './assets/logo.png';
// 传入hbs模板的参数对象
const templateParams = {
  logoUrl: logo
};

对应hbs模板写法:

<img src="{{logoUrl}}" alt="站点logo">

修改后完整配置参考

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

module.exports = {
  entry: './src/index.js',
  plugins: [
    new HtmlWebpackPlugin({
      title: 'Output Management',
      template: './src/index.hbs'
    }),
  ],
  devtool: 'inline-source-map',
  devServer: {
    static: './dist',
    hot: true,
  },
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/',
    clean: true,
  },
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
        generator: {
          filename: 'assets/img/[hash][ext][query]'
        }
      },
      {
        test: /\.hbs$/i,
        use: ['html-loader', 'handlebars-loader'],
      },            
    ],
  },
};

内容的提问来源于stack exchange,提问作者Victor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 18:54:04