Search code examples
gulpgulp-userefgulp-merge

gulp-useref does not work with gulp-merge


Situation: I have the following Gulp script, which should build all my html files to the distFolder. In addition it should build the external script files by parsing the links in index.html - this is what useref is good for. I am not sure if this is the ideal way to go - but I need to split the html files - if I put in multiple html files I get write conflicts with cleanCSS() and uglify().

// Parse the html file and create external scripts
gulp.task('htmlscripts', function() {
    var s1 = gulp.src(['*.html', '!index.html'])
        .pipe(useref({noAssets: true}))
        .pipe(gulp.dest(distFolder));
    var s2 = gulp.src('index.html')
        .pipe(useref())
        .pipe(cache('useref'))
        .pipe(gulpif('*.js', uglify()))
        .pipe(gulpif('*.css', cleanCSS()))
        .pipe(gulp.dest(distFolder));
    return merge(s1, s2);
});

// Minify 
gulp.task('htmlmin', ['htmlscripts'], function() {
    return ...
});

gulp.task('default', ['htmlscripts', 'htmlmin']);

Problem: The 2nd task (htmlmin) is never loaded. It seems, that the 1st task (htmlscripts) does not return a valid end in the promise. (Dependency problem)

If I remove one of the two tasks the other one finishes correctly.

I have done the following tests:

Not working (htmlmin task not started):

gulp.task('htmlscripts', function() {
    var s1 = gulp....
    var s2 = gulp....
    return merge(s1,s2);
});

Working (I mean at least the htmlmin script is run):

gulp.task('htmlscripts', function() {
    var s1 = gulp....
    var s2 = gulp....
    return merge(s1);
});

Not working (htmlmin task not started):

gulp.task('htmlscripts', function() {
    var s1 = gulp....
    var s2 = gulp....
    return merge(s2); // this one is really strange, isn't it? (see next test)
});

Working (I mean at least the htmlmin script is run):

gulp.task('htmlscripts', function() {
    // var s1 = gulp....
    var s2 = gulp....
    return merge(s2);
});

Solution

  • Are you using gulp-cached?

    Could it be, that your resource in s2 is found in the cache? Therefore .pipe(cache('useref')) won't pass the file forward and s2 will be null ?

    With gulp-cached, if a resource is found in the cache, it won't pass forward the cached resource. It passes nothing, i.e. it stops. Therefore s2 will be empty.

    I would try removing .pipe(cache('useref')) and see if it works?