How can I use Gulp to add a line of text to a file

做~自己de王妃 提交于 2019-11-29 03:46:20

Depends on what you want to do.

If you just want to add text to the beginning or end of a file gulp-header and gulp-footer are your friends:

var header = require('gulp-header');
var footer = require('gulp-footer');

gulp.task('add-text-to-beginning', function() {
  return gulp.src('src/css/main.sass')
    .pipe(header('@import \'plugins\'\n'))
    .pipe(gulp.dest('dist'));
});

gulp.task('add-text-to-end', function() {
  return gulp.src('src/css/main.sass')
    .pipe(footer('@import \'plugins\''))
    .pipe(gulp.dest('dist'));
});

If you have some kind of "anchor" text in your file you can use gulp-replace:

var replace = require('gulp-replace');

gulp.task('replace-text', function() {
  var anchor = '// Add Imports';
  return gulp.src('src/css/main.sass')
    .pipe(replace(anchor, anchor + '\n@import \'plugins\'\n'))
    .pipe(gulp.dest('dist'));
});

Finally there's the swiss army knife of vinyl file manipulation: map-stream. This gives you direct access to file contents and allows you to do any kind of string manipulation that you can think of in JavaScript:

var map = require('map-stream');

gulp.task('change-text', function() {
  return gulp.src('src/css/main.sass')
    .pipe(map(function(file, cb) {
      var fileContents = file.contents.toString();
      // --- do any string manipulation here ---
      fileContents = fileContents.replace(/foo/, 'bar');
      fileContents = 'First line\n' + fileContents;
      // ---------------------------------------
      file.contents = new Buffer(fileContents);
      cb(null, file);
    }))
    .pipe(gulp.dest('dist'));
});
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!