简体   繁体   English

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

[英]How I replace values in HTML attributes via config.json file with Gulp?

Let's say I have a JSON file with the pairs: 假设我有一个带有对的JSON文件:

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

then, I want to read those values and use them to replace attributes in an html file that looks like this: 然后,我想读取这些值,并使用它们替换如下所示的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>

So, with the html file in a "temp/" path, after gulping, I obtain a valid html file in "dist/" with the attributes changed looking like this: 因此,将html文件放在“ temp /”路径中,经过吞食后,我在“ dist /”中获得了一个有效的html文件,其属性已更改,如下所示:

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

I have already tried gulp-token-replace but after running it once, it won't work again if I save new values in the json file, even when it triggers the watch function, forcing me to restart the "gulp". 我已经尝试过gulp-token-replace,但是运行它一次之后,如果我将新值保存在json文件中,即使它触发了watch函数,也将无法再次工作,迫使我重新启动“ gulp”。

Is there a gulp plugin that can do this? 有一个gulp插件可以做到这一点吗? or a technique that can replace the gulp-token-replace? 或可以替换掉gulp-token-replace的技术?

Maybe just javascript, but, can I run something like that from inside a gulp process (running watch to refresh it)? 也许只是javascript,但是,我可以在gulp进程中运行类似的东西(运行手表以刷新它)吗?

Gulpfile.js as requested: 根据要求提供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']);
});

I received the answer directly from the developer of the Gulp Token Replace plugin, so I'm answering my own question for archive purposes. 我直接从Gulp令牌替换插件的开发人员那里得到了答案,因此出于存档目的,我在回答自己的问题。

Replace this: 替换为:

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

with this: 有了这个:

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

And now it works like a charm! 现在,它就像一种魅力!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何循环获取从 config.json 文件中获取的大量值 - How to loop for an amount of values got from a config.json file 在 Vue CLI 3 中运行 build:electron 后,如何将静态 config.json 文件中的值读取到 Vue 文件中的 TypeScript? - How can I read values from a static config.json file to TypeScript in a Vue file after running build:electron in Vue CLI 3? 如何从assets中的config.json文件中获取图片url并显示在angular中的index.html文件中 - How to get image url from config.json file in assets and display it in index.html file in angular 如何使用 discord.js 替换 `config.json` 列表中的字母? - How to replace letters from a list in `config.json` to noting using discord.js? 为什么我不能使用 RequireJS 解析 JavaScript 中的 config.json 文件? - Why can I not parse my config.json file in JavaScript using RequireJS? 错误:ENOENT:没有这样的文件或目录,打开“../config.json” - Error: ENOENT: no such file or directory, open '../config.json' 我不断收到错误:找不到模块'./config.json/' - I keep getting Error: Cannot find module './config.json/' Babel加载器未加载config.json文件 - Babel loader not loading form config.json file 无法读取node.js中的config.json文件 - Unable to read config.json file in node.js .env 与配置 json - .env vs config.json
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM