Как заменить значения в атрибутах HTML через файл config.json на Gulp?

1

Скажем, у меня есть файл 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 я получаю действительный html файл в "dist/" с измененными атрибутами, выглядящими так:

<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 файле, даже когда он вызывает функцию часов, заставив меня перезапустить "gulp".

Есть ли плагин для глотки, который может это сделать? или метод, который может заменить замену глотки-токена?

Может быть, просто javascript, но могу ли я запустить что-то подобное изнутри процесса глотки (запустить часы, чтобы обновить его)?

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']);
});
  • 0
    Примечание просто указывает на то, что вы не можете использовать регулярные выражения для поиска значений, подлежащих замене. Некоторые плагины могут использовать регулярные выражения. Так что это не ваша проблема. Нам также нужно увидеть ваш gulpfile.js, чтобы помочь. Я не вижу причин, по которым gulp-token-replace нельзя использовать в задаче с наблюдателем.
  • 0
    @mark Gulp-token-replace работает, проблема в том, что после первого запуска (чтение файла config.json с набором переменных) он не перезагружает файл config.json. Таким образом, весь процесс запускается, но переменные остаются прежними. Я собираюсь добавить gulpfile.js, чтобы он стал понятнее.
Теги:
gulp
gulp-watch

1 ответ

0
Лучший ответ

Я получил ответ напрямую от разработчика плагина Gulp Token Replace, поэтому я отвечаю на свой вопрос в архивных целях.

Замените это:

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

с этим:

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

И теперь это работает как шарм!

Ещё вопросы

Сообщество Overcoder
Наверх
Меню