Question

I have a Gulp task that renders a file containing a Lodash template and puts it in my build directory. I use gulp-template to do the rendering.

To render correctly, my template needs to be passed a list of files from my build directory. I get this list using glob. Since the glob API is asynchronous, I'm forced to write my task like this:

gulp.task('render', function() {
    glob('src/**/*.js', function (err, appJsFiles) {

        // Get rid of the first path component.
        appJsFiles = _.map(appJsFiles, function(f) {
            return f.slice(6);
        });

        // Render the file.
        gulp.src('src/template.html')
            .pipe(template({
                scripts: appJsFiles,
                styles: ['style1.css', 'style2.css', 'style3.css']
            }))
            .pipe(gulp.dest(config.build_dir));
    });
});

This seems inelegant to me. Is there a better way to write this task?

Was it helpful?

Solution

The easiest way to fix your specific problem is to use the synchronous mode for glob, which is in the docs you linked to. Then return the result of gulp.src.

gulp.task('render', function() {
    var appJsFiles = _.map(glob.sync('src/**/*.js'), function(f) {
        return f.slice(6);
    });
    // Render the file.
    return gulp.src('src/template.html')
        .pipe(template({
            scripts: appJsFiles,
            styles: ['style1.css', 'style2.css', 'style3.css']
        }))
        .pipe(gulp.dest(config.build_dir));
});

OTHER TIPS

If you want a task to run asynchronously, take in a callback.

gulp.task('render', function(cb) {
    glob('src/**/*.js', function (err, appJsFiles) {
        if (err) {
            return cb(err);
        }

        // Get rid of the first path component.
        appJsFiles = _.map(appJsFiles, function(f) {
            return f.slice(6);
        });

        // Render the file.
        gulp.src('src/template.html')
            .pipe(template({
                scripts: appJsFiles,
                styles: ['style1.css', 'style2.css', 'style3.css']
            }))
            .pipe(gulp.dest(config.build_dir))
            .on('end', cb);
   });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top