0

I'm trying to minify my HTML. I've just discovered and started using the gulp-htmlmin plugin

My gulp task...

gulp.task('build-html',function(){
    return gulp.src(appDev+'test.html')
        .pipe(htmlmin({collapseWhitespace: true}))
        .pipe(gulp.dest(appProd));
});

fails when applied to this valid HTML, or any document with the < character:

<div> < back </div>

The error is:

Error: Parse Error: < back </div>
    at new HTMLParser (html-minifier\src\htmlparser.js:236:13)

I can think of two solutions:

  • Replace < with &lt; in all my templates. Doing so manually won't be fun, but that's life. Any idea how to do it in a gulp task?

  • Ditch this plugin in search for one that can parse and minify my templates. Any suggestions?

Guess I'm wondering how someone more experienced at building for deployment (I'm new) would handle this.

Community
  • 1
  • 1
BeetleJuice
  • 39,516
  • 19
  • 105
  • 165

2 Answers2

1

I'm afraid you're going to have to change them to &lt;. The html-minifier team has specifically stated they won't support bare <s.

You want do this anyway, both to not trip up parsers and to protect against certain XSS attacks. See

for more info.

The good news is any text editor worth its coding salt supports project-wide or at least multi-file search and replace. Assuming all your HTML <tags> don't have whitespace after the <, you should be able to just replace "< " with "&lt; ".

Community
  • 1
  • 1
henry
  • 4,244
  • 2
  • 26
  • 37
  • 1
    Thanks. After posting I came to the same conclusion. I was too scared to trust find & replace though so I did what my answer lays out. – BeetleJuice Sep 10 '16 at 07:14
0

I decided to replace all < with &lt; since I figured this will probably save me some grief down the road. Besides @henry made great points in his answer.

I was too big of a chicken though to trust my IDE to do a find and replace without breaking my code all kinds of ways. Instead I followed these steps:

  1. Run gulp task from the OP
  2. Notice the file that threw the parse error and go fix it
  3. Run gulp task again
  4. A new file throws the parse error. Go fix it
  5. ...

Eventually I fixed all the files.

BeetleJuice
  • 39,516
  • 19
  • 105
  • 165
  • Better safe than sorry! I'm sure others have their own favorites, but my favorite UI for multi-file find/replace is in BBEdit (paid)/TextWrangler (free) (I'm not affiliated with Bare Bones) – henry Sep 10 '16 at 22:08