我如何使用Gulp通过config.json文件替换HTML属性中的值?

时间:2018-01-04 14:37:02

标签: javascript json gulp gulp-watch gulp-cheerio

假设我有一个带有对的JSON文件:

{
  "Table":{
    "fullwidth": "680",
    "color": "#33d025",
    "margin1": "30",
    "margin2": "60",
    "padding": "20"
  }
}

然后,我想读取这些值并使用它们来替换html文件中的属性,如下所示:

<table width="{{Table.fullwidth}}" bgcolor="{{Table.color}}" style="margin: {{Table.margin1}}px {{Table.margin2}}px;">
  <tr>
    <td style="padding: {{Table.padding}}px;">
      <img src="a.jpg">
    </td>
  </tr>
</table>

所以,将html文件放在“temp /”路径中,在gulping之后,我在“dist /”中获取一个有效的html文件,其属性改变如下:

<table width="680" bgcolor="#33d025" style="margin: 30px 60px;">
  <tr>
    <td style="padding: 20px;">
      <img src="a.jpg">
    </td>
  </tr>
</table>

我已经尝试过gulp-token-replace但是在运行一次之后,如果我在json文件中保存新值,它将无法再次工作,即使它触发了watch功能,也迫使我重启“gulp”

有没有可以做到这一点的gulp插件?或者可以替换gulp-token-replace的技术?

也许只是javascript,但是,我可以在gulp进程中运行类似的东西(运行watch来刷新它)吗?

根据要求提供Gulpfile.js:

// Include gulp
var gulp = require('gulp'),

// Include plugins
fileinclude = require('gulp-file-include'),
rename = require('gulp-rename'),
images = require('gulp-imagemin'),
cache = require('gulp-cache'),
browserSync = require('browser-sync').create(),
reload = browserSync.reload,
runSequence = require('run-sequence'),
del = require('del'),
notify = require('gulp-notify'),
gtr = require('gulp-token-replace')

// Default Task
gulp.task('default', function (cb) {
runSequence('clean', ['AA', 'BB', 'CC', 'watch'], cb);
});

// TASKS

// Clean 'dist'
gulp.task('clean', function () {
return del(['HTMLTemplates/*.html', 'HTMLTemplates/img', 'Temp/*.html']);
});

// Compress images
gulp.task('BB', function () {
gulp.src('templates/img/*.{gif,jpg,png}')
    .pipe(cache(images({
        optimizationLevel: 4,
        progressive: true,
        interlaced: true
    })))
    .pipe(gulp.dest('Templates/img/'));
});

// Reload browser
gulp.task('reload', function () {
browserSync.reload();
});

// Prepare Browser-sync
gulp.task('CC', ['AA'], function () {
browserSync.init({
    // browserSync.init(['templates/*/*.html'], {
    //proxy: 'your_dev_site.url'
    server: {
        baseDir: './HTMLTemplates'
    }
});
});

// MAIN TASKS

gulp.task('AA', function (cbk) {
runSequence('fileinclude', 'trp', cbk);
});

// Force to run fileinclude first before replacing the tokens
gulp.task('trp', ['fileinclude'], function (done) {
function onFinish(event) {
    if (event.task === 'tokenreplace') {
        gulp.removeListener('task_stop', onFinish);
        done();
    }
}
gulp.on('task_stop', onFinish);
gulp.start('tokenreplace');
});

// Include partial files into email template (fileinclude)
gulp.task('fileinclude', function () {
// grab 'template'
return gulp.src('templates/layouts/*.tpl.html')
    // include partials
    .pipe(fileinclude({
        basepath: 'templates/components/'
    }))
    // remove .tpl.html extension name
    .pipe(rename({
        extname: ""
    }))
    // add new extension name
    .pipe(rename({
        extname: ".html"
    }))
    // move file to folder
    .pipe(gulp.dest('Temp/'))
    .pipe(notify({
        message: 'Template file includes complete'
    }));
});

// Replace tokens in the index.html created by fileinclude
gulp.task('tokenreplace', ['fileinclude'], function (doit) {
var config = require('./templates/components/000 vars/config.json');
return gulp.src('Temp/index.html')
    .pipe(gtr({
        global: config
    }))
    .pipe(gulp.dest('HTMLTemplates/'))
    // notify to say the task has complete
    .pipe(browserSync.stream())
    .pipe(notify({
        message: 'Vars includes complete'
    })), doit();
});

// END of MAIN TASKS

// WATCH

// Watch files for changes in html/css/tpl.html/images
gulp.task('watch', function () {
gulp.watch(['templates/components/**/*.html'], ['AA']);
gulp.watch(['templates/components/**/*.css'], ['AA']);
gulp.watch(['templates/layouts/*.tpl.html'], ['AA']);
gulp.watch(['templates/components/000 vars/*.json'], ['trp']);
gulp.watch(['HTMLTemplates/*.html'], ['reload']);
gulp.watch('templates/img/*', ['BB']);
});

1 个答案:

答案 0 :(得分:0)

我直接从Gulp Token Replace插件的开发者那里得到了答案,所以我正在回答我自己的问题以进行存档。

替换它:

PDOs

用这个:

// Replace tokens in the index.html created by fileinclude
gulp.task('tokenreplace', ['fileinclude'], function (doit) {
  var config = require('./templates/components/000 vars/config.json');
  return gulp.src('Temp/index.html')
  .pipe(gtr({
  global: config
}))

现在它就像一个魅力!