1

Our project is using Gulp. Now I have a requirement: we have multiple page-level HTML files, say login.html and my.html. Inside these original HTML files there is a variable called {{PAGE_TITLE}}, which should be replaced (by Gulp) to be "Login to System" and "My Account" respectively. Here is my current script:

gulp.task('pages', ['clean:tmp'], function () {
    var pageTitle = '';
    return gulp.src('/my/source/html/**/*.html')
        .pipe(tap(function (file, t) {
            pageTitle = /index.html$/.test(file.path) ? 'Login to System' : 'My Account';
        }))
        .pipe(replace(/{{PAGE_TITLE}}/g, pageTitle))
        .pipe(gulp.dest('/my/dest/'));
});

It turns out the variable pageTitle is never set before the replace. I have searched for documentation of gulp-tap for tons of times, but I still do not know how to make it work. Please help, thanks.

This post: Modify file in place (same dest) using Gulp.js and a globbing pattern tries to achieve the same affect, but he resulted in some other solution.

Community
  • 1
  • 1
Joy
  • 9,430
  • 11
  • 44
  • 95
  • Never used that gulp package before, if it was me i'd probably be using [gulp-if](https://www.npmjs.com/package/gulp-if) and [gulp-html-replace](https://www.npmjs.com/package/gulp-html-replace). A little less clean cuz it doesnt use moustache. Have you tried setting pageTitle as a global variable of `module.exports`? – marblewraith Feb 04 '16 at 08:31
  • Thanks. We store the pageTitle in a separate JSON file. I load it to gulp. The problem is the variable should be replaced based on the file name dynamically. The two plugins seem not suitable for this scenario. – Joy Feb 04 '16 at 08:47
  • `gulp-tap` allows me to access the file name from `gulp.src` – Joy Feb 04 '16 at 08:48

1 Answers1

5

I figured out the solution as followed:

gulp.task('pages', ['clean:tmp'], function () {

    function replaceDynamicVariables(file) {
        var pageTitle = /login.html$/.test(file.path) ? 'Login to System' : 'My Account';
        file.contents = new Buffer(String(file.contents)
            .replace(/{{PAGE_TITLE}}/, pageTitle)
        );
    }

    return gulp.src('/my/source/html/**/*.html')
        .pipe(tap(replaceDynamicVariables))
        .pipe(gulp.dest('/my/dest/'));
});
Joy
  • 9,430
  • 11
  • 44
  • 95