Minify HTML, but don't touch PHP with Gulp
The gulp-htmlmin module uses the html-minifier module, which has plenty of options (displayed on both its npmjs.com and github pages) that can be used. The option we will focus on is ignoreCustomFragments
.
var gulp = require(gulp), htmlmin = require(gulp-htmlmin);gulp.task('htmltask', function(){ return gulp.src(['./dev/*.html','./dev/*.php']) .pipe(htmlmin({ collapseWhitespace: true, ignoreCustomFragments: [ /<%[\s\S]*?%>/, /<\?[=|php]?[\s\S]*?\?>/ ] })) .pipe(gulp.dest('./site'));});
In the above code, you see we are using ignoreCustomFragments
with the regex /<\?[=|php]?[\s\S]*?\?>/
to ignore code starting with <?
and <?php
and ending with ?>
.
By default, html-minifier ignores php, so you don't have to worry about setting ignoreCustomFragments
.
EDITThanks amersk
Some php files you work with may not have closing tags, for example many WordPress files do not. An alternative would be to use the following instead:
ignoreCustomFragments: [/<\?[\s\S]*?(?:\?>|$)/]
This works for me !
// Gulp.js configurationvar // modules gulp = require('gulp'), newer = require('gulp-newer'), htmlmin = require('gulp-htmlmin') // development mode? devBuild = (process.env.NODE_ENV !== 'production'), // folders folder = { src: 'src/', build: 'build/' } gulp.task('minify', () => { return gulp.src('src/*.html') .pipe(htmlmin({ collapseWhitespace: true })) .pipe(gulp.dest('dist')); });;