插件:gulp-htmlmin(gulp-html-minify
is deprecated)
执行安装命令:$ cnpm install gulp-htmlmin --save-dev
var htmlmin=require('gulp-htmlmin');
gulp.task('useref',function(){
return gulp.src('src/index.html')
.pipe(useref())
.pipe(htmlmin({ collapseWhitespace: true }))
.pipe(gulpIf('*.css',cleanCSS()))
.pipe(gulpIf('*.js',uglify()))
.pipe(gulp.dest('dist'))
})
执行:$ gulp useref
,这时会发生什么呢?
events.js:183
throw er; // Unhandled ‘error’ event
^
Error: Parse Error: <[\w\W]+>)[^>]|#([\w-]*))$/,C=/^<(\w+)\s/?>(?:</\1>|)$/,k=/^[],:{}\s]$/,E=/(?:^|:|,)(?:\s[)+/g,S=/\(?:[“\/bfnrt]|u[\da-fA-F]{4})/g,A=/“[^”\\r\n]*”|true|false|null|-?(?:\d+.|)\d+(?:[eE][+-]?\d+|)/g,j=/^-ms-/,D=/-([\da-z])/gi,L=function(e,t){return t.toUpperCase()},H=function(e){(o.addEventListener||”load”===e.type||”complete”===o.readyState)&&(q(),b.ready())},q=………………………………………………………………………………………………………………………………………………………………………………………
一长串的错误,错误中实在找不到什么有用的信息,在 gulp-htmlmin
的 Issues
一时没找到解决方法,反而在 gulp-useref
的 Issues
找到了答案,这个 issue
中,gulp-htmlmin
的作者是这样说的,没错,就是gulp-htmlmin
的作者,哈哈……
I created the same gulpfile and tried to run it. It throws an error which is very similar to the one @elado ran into.
events.js:72 throw er; // Unhandled 'error' event ^ Error: no writecb in Transform class ( ... )
And, after I updated the task to
.pipe($.if('*.html', $.htmlmin()))
, it doesn’t throw any errors.
于是,把上面的代码改成这样:
gulp.task('useref',function(){
return gulp.src('src/index.html')
.pipe(useref())
.pipe(gulpIf('*.html',htmlmin({ collapseWhitespace: true })))
.pipe(gulpIf('*.css',cleanCSS()))
.pipe(gulpIf('*.js',uglify()))
.pipe(gulp.dest('dist'))
})
再来执行:$ gulp useref
。
执行OK!