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

使用Gulp压缩HTML时gulp-inject注释被移除,求解决方法

解决Gulp压缩HTML后gulp-inject注释消失的问题

这个问题的核心原因是你使用的$.minifyHtml()(对应gulp-minify-html插件)默认会清除所有HTML注释,而gulp-inject正是依赖<!-- inject:js -->和<!-- endinject -->这些注释标记来识别注入位置的,所以压缩后这些标记就被删掉了。

要解决这个问题,你只需要给minifyHtml添加配置选项,明确保留这些inject相关的注释即可。下面是修改后的html任务代码:

gulp.task('html', function() {
  var assets = $.useref.assets({searchPath: '{.tmp,app}'});
  return gulp.src('app/**/**/*.html')
    .pipe(assets)
    // Remove Any Unused CSS
    // Note: If not using the Style Guide, you can delete it from
    // the next line to only include styles your project uses.
    .pipe($.if('*.css', $.uncss({
      html: [ 'app/index.html' ],
      // CSS Selectors for UnCSS to ignore
      ignore: []
    })))
    // Concatenate And Minify Styles
    // In case you are still using useref build blocks
    .pipe($.if('*.css', $.csso()))
    .pipe(assets.restore())
    .pipe($.useref())
    // Minify Any HTML - 修改这里,添加注释保留配置
    .pipe($.if('*.html', $.minifyHtml({
      // 保留符合指定正则的注释
      ignoreCustomComments: [/^\s*inject:/, /^\s*endinject/],
      // 可选:如果需要保留其他普通注释,可以开启这个选项
      // comments: true
    })))
    // Output Files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

配置说明:

  • ignoreCustomComments:接受一个正则数组,匹配到的注释会被保留不删除。这里的两个正则分别匹配<!-- inject:... -->和<!-- endinject -->(允许注释前有空格),确保gulp-inject的标记不会被清除。
  • 如果你希望保留所有HTML注释,可以额外添加comments: true选项,但通常只保留必要的inject标记就足够了。

这样修改后,执行压缩任务时,gulp-inject的注释标记会被保留下来,后续如果需要重新执行注入操作也能正常工作。

内容的提问来源于stack exchange,提问作者Pyae Phyoe Shein

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:32:07