Gulp:根据文件名替换HTML文件中的变量
Gulp: replace variables in HTML file based on file name
我们的项目正在使用 Gulp。现在我有一个要求:我们有多个页面级 HTML 文件,比如 login.html
和 my.html
。在这些原始 HTML 文件中有一个名为 {{PAGE_TITLE}}
的变量,应将其替换(由 Gulp
)分别为 "Login to System"
和 "My Account"
。这是我当前的脚本:
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/'));
});
事实证明变量 pageTitle
从未在 replace
之前设置。我已经搜索了很多次 gulp-tap
的文档,但我仍然不知道如何让它工作。请帮忙,谢谢。
这个post:Modify file in place (same dest) using Gulp.js and a globbing pattern试图达到同样的效果,但他得出了一些其他的解决方案。
我想出了如下解决方案:
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/'));
});
我们的项目正在使用 Gulp。现在我有一个要求:我们有多个页面级 HTML 文件,比如 login.html
和 my.html
。在这些原始 HTML 文件中有一个名为 {{PAGE_TITLE}}
的变量,应将其替换(由 Gulp
)分别为 "Login to System"
和 "My Account"
。这是我当前的脚本:
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/'));
});
事实证明变量 pageTitle
从未在 replace
之前设置。我已经搜索了很多次 gulp-tap
的文档,但我仍然不知道如何让它工作。请帮忙,谢谢。
这个post:Modify file in place (same dest) using Gulp.js and a globbing pattern试图达到同样的效果,但他得出了一些其他的解决方案。
我想出了如下解决方案:
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/'));
});