gulp常用插件之gulp-replace使用


更多gulp常用插件使用請訪問:gulp常用插件匯總


gulp-replace這是一款gulp3的字符串替換插件。

更多使用文檔請點擊訪問gulp-replace工具官網

安裝

一鍵安裝不多解釋

npm install --save-dev gulp-replace

使用

簡單的字符串替換

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

gulp.task('templates', function(){
  gulp.src(['file.txt'])
    .pipe(replace('bar', 'foo'))
    .pipe(gulp.dest('build/'));
});

簡單的正則表達式替換

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

gulp.task('templates', function(){
  gulp.src(['file.txt'])
    // See https://mdn.io/string.replace#Specifying_a_string_as_a_parameter
    .pipe(replace(/foo(.{3})/g, '$1foo'))
    .pipe(gulp.dest('build/'));
});

字符串替換為函數回調

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

gulp.task('templates', function(){
  gulp.src(['file.txt'])
    .pipe(replace('foo', function(match) {
      //替換“foo”的實例為“oof”
      return match.reverse();
    }))
    .pipe(gulp.dest('build/'));
});

正則表達式替換為函數回調

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

gulp.task('templates', function(){
  gulp.src(['file.txt'])
    .pipe(replace(/foo(.{3})/g, function(match, p1, offset, string) {
      // 用barbaz替換foobaz並記錄大量信息
      // See https://mdn.io/string.replace#Specifying_a_function_as_a_parameter
      console.log('Found ' + match + ' with param ' + p1 + ' at ' + offset + ' inside of ' + string);
      return 'bar' + p1;
    }))
    .pipe(gulp.dest('build/'));
});

帶文件對象的函數回調

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

gulp.task('templates', function(){
  gulp.src(['file.txt'])
    .pipe(replace('filename', function() {
       //替代對象的“文件名”的實例為“file.txt的” 
      // this.file也可用於正則表達式替換
      //參見https://github.com/gulpjs/有關可用屬性的詳細信息乙烯#實例的屬性
      return this.file.relative;
    }))
    .pipe(gulp.dest('build/'));
});

API

gulp-replace可以用字符串或正則表達式調用。

replace(string, replacement[, options])

  • string
    類型: String
    要搜索的字符串。
  • replacement
    類型:StringFunction
    替換字符串或函數。如果replacement是函數,則每次匹配都會調用一次,並將傳遞要替換的字符串。
    this.file的值將等於正在處理的文件的vinyl instance實例。

replace(regex, replacement[, options])

  • regex
    類型: RegExp
    要搜索的正則表達式模式。
  • replacement
    類型:StringFunction
    替換字符串或函數。有關特殊替換字符串模式和替換函數參數的詳細信息
    this.file的值將等於正在處理的文件的vinyl instance實例。

gulp-replaceoptions
options是可選的第三個參數。

  • options
    類型: Object
  • options.skipBinary
    類型:boolean
    默認值:true
    跳過二進制文件。默認情況下,此選項為true。如果要替換二進制文件中的內容,則必須將其顯式設置為false


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM