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

使用html-minifier时出现TypeError: htmlmin不是函数的问题求助

解决html-minifier在Gulp任务中报错TypeError: htmlmin is not a function的问题

问题原因

html-minifier是普通Node.js工具库,核心功能是通过minify方法处理HTML字符串,但并非为Gulp流设计的插件,无法直接通过.pipe()调用,这就是报错的根本原因。

解决方案1:使用专门的Gulp插件(推荐)

改用gulp-htmlmin——基于html-minifier封装的Gulp专属插件,直接适配Gulp流处理:

  1. 安装插件
npm install gulp-htmlmin --save-dev
  1. 修改引入和任务代码
import htmlmin from 'gulp-htmlmin';

export const html = () => {
  return gulp.src("source/*.html")
    .pipe(htmlmin({ collapseWhitespace: true }))
    .pipe(gulp.dest("build"));
}

原有任务逻辑可完全保留,直接运行即可正常压缩HTML。

解决方案2:手动包装原生html-minifier为流处理函数

若坚持使用原生html-minifier,需借助through2将其包装成Gulp可识别的流转换函数:

  1. 安装依赖
npm install through2 --save-dev
  1. 修改任务代码
import htmlmin from 'html-minifier';
import through2 from 'through2';

export const html = () => {
  return gulp.src("source/*.html")
    .pipe(through2.obj(function(file, enc, cb) {
      // 处理Buffer类型的文件
      if (file.isBuffer()) {
        const htmlContent = file.contents.toString();
        // 调用html-minifier的minify方法压缩
        const minifiedContent = htmlmin.minify(htmlContent, { collapseWhitespace: true });
        // 替换文件内容为压缩后的结果
        file.contents = Buffer.from(minifiedContent);
      }
      cb(null, file);
    }))
    .pipe(gulp.dest("build"));
}

内容的提问来源于stack exchange,提问作者Даниил Дашкевич

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 22:38:15