【问题标题】:Gulp - loop within pipeGulp - 管道内的循环
【发布时间】:2021-12-09 13:22:08
【问题描述】:

我正在使用 gulp-replace 来修改静态 html。

搜索和文本值存储在一个数组中:

const stringReplace = require ( 'gulp-replace' );

const textValues = [
    [ 'global-app-title', 'My App Title' ],
    [ 'global-app-version', '01.01.00' ],
    [ 'global-comp-name', 'ABC Company, LLC' ],
    [ 'global-comp-name-logo', 'ABC' ],
    [ 'global-comp-brand', 'Marketing Solutions...' ],
etc...
];

基本实现(数组中的单个元素)

gulp-replace 适用于 textValues 的单个索引:

gulp.task ( 'update-html-custom:dist', function () {
    return gulp.src ( [ paths.src.custom.html + '/**/*.html' ] )

        .pipe ( stringReplace ( textValues[ 1 ][ 0 ], textValuess [ 1 ][ 1 ] ) )
        .pipe ( gulp.dest ( paths.dist.custom.html ) )
} );

循环遍历数组

我正在尝试修改 gulp .pipe 命令以循环遍历 textValues 中的每个元素。但是,我的大多数 html 文件都会有多个匹配项(相同或不同的搜索字符串),所以我相信 gulp-replace 管道中需要某种循环 - 我必须在我交出之前更新匹配项的所有实例到 gulp.dest。

This post 建议 gulp-replace 可以带一个函数,所以我尝试了以下方法,但它出错了 'TypeError: dest.on is not a function':

gulp.task ( 'update-html-custom:dist', function () {
    return gulp.src ( [ paths.src.custom.html + '/**/*.html' ] )
        .pipe ( textValues.map ( (item) =>{
            stringReplace( item[ 1 ][ 0 ], item [ 1 ][ 1 ] )
            }))
        .pipe ( gulp.dest ( paths.dist.custom.html ) )
} );

有没有办法在管道命令中循环遍历我的数组?

【问题讨论】:

    标签: arrays gulp str-replace


    【解决方案1】:

    解决方案

    这可能不是最严格的代码,但它似乎可以工作:

    const gulpEach = require ( 'gulp-each' );
    
    const textValues = [
        [ 'global-app-title', 'My App Title' ],
        [ 'global-app-version', '01.01.00' ],
        [ 'global-comp-name', 'ABC Company, LLC' ],
        [ 'global-comp-name-logo', 'ABC' ],
        [ 'global-comp-brand', 'Marketing Solutions...' ],
    etc...
    ];
    
    
    gulp.task ( 'update-html-custom:dist', function () {
        return gulp.src ( [ paths.src.custom.html + '/**/*.html' ] )
            .pipe ( gulpDebug ( {title: 'file name: '} ) )
    
            .pipe ( gulpEach ( function ( content, file, callback ) {
                let updatedContent = content;
    
                textValues.forEach ( ( item ) => {
                    let textPos = updatedContent.search ( item[ 0 ] );
    
                    while ( textPos >= 0 ) {
                        updatedContent = updatedContent.replace ( item[ 0 ], item[ 1 ] );
                        textPos = updatedContent.search ( item[ 0 ] );
                    }
                } )
                callback ( null, updatedContent );
            } ) )
    
            .pipe ( gulp.dest ( paths.dist.custom.html ) )
            .pipe ( browserSync.reload ( { stream: true } ) )
    } );
    
    

    gulp-each 有段时间没更新了,不过看起来还算稳定……

    【讨论】:

      猜你喜欢
      • 2015-01-26
      • 2021-07-01
      • 1970-01-01
      • 2014-08-06
      • 2021-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多