如何使用gulp修改配置文件

时间:2015-07-06 16:51:07

标签: gulp

我使用gulp配置复杂的本地设置,需要自动编辑文件。

场景是:

  • 确定某个文件是否包含某些其他行之后的某些行(使用正则表达式找到)
  • 如果找不到行,请插入该行。
  • 可选择删除文件中的一些行。

我需要这个来修改系统配置文件和编译方案。

在gulp中做到这一点最好的方法是什么?

2 个答案:

答案 0 :(得分:3)

Gulp是简单的javascript。所以如果我是你,我会做的是创建一个插件来管道到原始的配置文件。

Gulp流发出Vinyl个文件。因此,您真正要做的就是创建一个“管道工厂”来转换对象。

它看起来像这样(使用EventStream):

var es = require('event-stream');

// you could receive params in here if you're using the same
// plugin in different occasions.
function fixConfigFile() {
  return es.map(function(file, cb) {
    var fileContent = file.contents.toString();

    // determine if certain file contains certain lines...
    // if line is not found, insert the line.
    // optionally, delete some lines found in the file.

    // update the vinyl file
    file.contents = new Buffer(fileContent);

    // send the updated file down the pipe
    cb(null, file);
  });
}

gulp.task('fix-config', function() {
  return gulp.src('path/to/original/*.config')
    .pipe(fixConfigFile())
    .pipe(gulp.dest('path/to/fixed/configs');
});

答案 1 :(得分:0)

或者您可以使用vinyl-map

const map = require('vinyl-map')
const gulp = require('gulp')

const modify = map((contents, filename) => {
    contents = contents.toString()

    // modify contents somehow

    return contents
  })

gulp.task('modify', () =>
  gulp.src(['./index.js'])
    .pipe(modify)
    .pipe(gulp.dest('./dist'))
})