2016-02-04 81 views
0

我們的項目使用Gulp。現在我有一個要求:我們有多個頁面級HTML文件,例如login.htmlmy.html。在這些原始HTML文件中,有一個名爲{{PAGE_TITLE}}的變量,應該分別替換(Gulp)爲"Login to System""My Account"。這裏是我當前的腳本:Gulp:根據文件名替換HTML文件中的變量

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/')); 
}); 

原來變量pageTitlereplace之前從未設置。我已經搜索了很多次的文檔gulp-tap,但我仍然不知道如何使其工作。請幫忙,謝謝。

這篇文章:Modify file in place (same dest) using Gulp.js and a globbing pattern試圖實現同樣的影響,但他導致了一些其他的解決方案。

+0

之前從未使用過一口包,如果是我我可能會使用[吞掉-IF](https://www.npmjs.com/package/gulp-if)和[gulp-html-replace](https://www.npmjs.com/package/gulp-html-replace)。不那麼幹淨因爲它不使用鬍子。您是否嘗試將pageTitle設置爲'module.exports'的全局變量? –

+0

謝謝。我們將pageTitle存儲在單獨的JSON文件中。我加載它吞噬。問題是應該根據文件名動態地替換變量。這兩個插件似乎不適合這種情況。 – Joy

+0

'gulp-tap'允許我從'gulp.src'訪問文件名 – Joy

回答

1

我想出的解決方案如下:

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/')); 
}); 
相關問題