How to get gulp-html-minifier's output into gu

2019-09-13 02:39发布

问题:

I'm trying to use these two gulp plugins together:

  • gulp-html-minifier
  • gulp-inject-stringified-html

Or put differently, I'm trying to inject the contents of files containing html fragments into my javascript files after they're minified.

When I'm trying to run a straight up gulp build I get this:

Error: ENOENT: no such file or directory, open 'C:\path\to\.temp\template.html'

Here's a repro of my situation. My folder structure:

/src/app.js
/src/template.html
/gulpfile.js
/package.json

My gulpfile.js:

var gulp = require('gulp');
var injectHtml = require('gulp-inject-stringified-html');
var htmlmin = require('gulp-html-minifier');

gulp.task('minify', [], function() {
    gulp.src('src/*.html')
        .pipe(htmlmin())
        .pipe(gulp.dest('.temp'));
});

gulp.task('default', ['minify'], function() {
    gulp.src('src/*.js')
        .pipe(injectHtml())
        .pipe(gulp.dest('.build'));
});

The template.html file:

<div>My Template</div>

The app.js file:

var html = { gulp_inject: "../.temp/template.html" };

Now, if I run minify manually first, things will work as expected. From this I speculate I'm not using Gulp correctly. I reckon I'd need to pipe the result of htmlmin into the injectHtml method. But I fail to see how.

How can I get these two plugins to play together nicely?

回答1:

You are missing a return in the minify task. It should look like that:

gulp.task('minify', [], function() {
    return gulp.src('src/*.html')
        .pipe(htmlmin())
        .pipe(gulp.dest('.temp'));
});

Without return, the default task doesn't have any way to know that minify finished, so it may start before the minified html file was created.



标签: gulp