是否有可能在gulp中将变量从html抛出到gulp并将其加载到特定文件夹中?

时间:2017-09-20 06:09:40

标签: html gulp

//index.html
@@variable = 'free'


//inde-two.html
@@variable = 'pro'

我想在build / free文件夹中加载index.html 和build-pro.html中的index-two.html。

//gulp pseudo code
gulp.task('test',function(){
  if(variable == 'free');
    gulp.dest('build/free');
  if(variable == 'pro')
    gulp.dest('build/pro')
});

1 个答案:

答案 0 :(得分:0)

您需要阅读这些html文件并提取变量。以下是一些快速入门代码:

var fs = require('fs');

const index1 = 'index.html';
const index2 = 'index-two.html';

gulp.task("move-html", function () {

  var firstFile;
  var secondFile;
  var var1;
  var var2; 
  var re = /@@variable\s*=\s*('.*')/ig;

  firstFile= fs.readFileSync(index1, 'utf8');
  secondFile = fs.readFileSync(index2 'utf8');

  // now firstFile and secondFile are just strings that you can manipulate to get that @@variable.

  var1 = re.exec(firstFile)[1];
  var2 = re.exec(secondFile)[1]; 

  // var1 and var2 should now have your @@variable values from the two html files.

  if (var1 === 'free') {
      gulp.src(['index.html'])
        .pipe(gulp.dest('build/free'));
  }
  else if (var1 === 'pro')  {
      gulp.src(['index.html'])
        .pipe(gulp.dest('build/pro'));
  }

  if (var2 === 'free') {
      gulp.src(['index-two.html'])
        .pipe(gulp.dest('build/free'));
  }
  else if (var2 === 'pro')  {
      gulp.src(['index-two.html'])
        .pipe(gulp.dest('build/pro'));
  }
});

考虑这个未经测试的伪代码。它的一部分可能不会按原样运行,但它应该让你开始。