【问题标题】:How to search a string from a file and replace it to another with Gulp如何从文件中搜索字符串并用 Gulp 将其替换为另一个
【发布时间】:2017-10-22 19:53:59
【问题描述】:

我想使用 Gulp 从文件 test1.js 中获取选择器并将其替换为 test2.js

test1.js

@Component({
    selector: 'app-root',
    ...
})
export class AppComponent {}

所以,我想从 test1.js

获取“app-root”

test2.js

var selector = "#selector"
function() {}

test2.js 中,我想将“#selector”替换为“app-root”。

我知道如何用文件中的另一个字符串替换一个字符串:

gulp.src('test2.js', {base: 'src/'})
.pipe(replace(new RegExp(/#selector/, 'g'), (match, p1) => {
    return 'app-root';
}))
.pipe(gulp.dest('dist'));

但我不知道如何将“app-root”传递给流替换。

我怎么能用 Gulp 做到这一点?

谢谢!

【问题讨论】:

    标签: javascript search replace gulp match


    【解决方案1】:

    我找到了如何使用 ma​​p-stream

    var gulp = require('gulp');
    var map = require('map-stream');
    var fs = require('fs');
    
    gulp.task('default', function() {
        gulp.src('./test1.js')
            .pipe(map(function(file, callback) {
                var test = file.contents.toString().match(/selector: '(.*)'/i);
                fs.readFile('./test2.js', function read(err, data) {
                    if (test) {
                        fs.writeFile('./test2.js', data.toString().replace('#selector', test[1]));
                    }
                });
            }));
    });
    

    【讨论】:

      猜你喜欢
      • 2010-09-29
      • 1970-01-01
      • 2012-07-17
      • 2019-03-28
      • 1970-01-01
      • 2022-08-17
      • 2020-01-06
      • 2012-07-08
      • 1970-01-01
      相关资源
      最近更新 更多