2016-04-15 51 views
0

我不知道在做出如下代碼工作:如何通過陣列GULP任務循環

var language = ['en', 'sp']; 

gulp.task('jsonResourcesConcat', function() { 
    return gulp.src('path/to/json/' + language + '/resources.json') 
    .pipe(insert.prepend('window.resourcesData.' + language + ' = ')) 
    .pipe(concat('resources-' + language +'.js')) 
    .pipe(gulp.dest('./www/assets/json2js/')); 
}); 

我需要的文件應該是輸出到文件夾./www/assets/json2js/與文件名的資源恩.js文件和‘資源 - sp.js’

+0

你既需要在任務執行或每種語言需要自己任務? – MarcoL

回答

4

好吧,讓我們從你的腳本開始:

var languages = ['en', 'sp']; 

// this is the function that does all the work 
function buildJson(language) { 
    return gulp.src('path/to/json/' + language + '/resources.json') 
    .pipe(insert.prepend('window.resourcesData.' + language + ' = ')) 
    .pipe(concat('resources-' + language +'.js')) 
    .pipe(gulp.dest('./www/assets/json2js/')); 
}); 

現在安裝EventStream模塊能夠輕鬆地處理流:

$ npm install event-stream 

並用它來管咕嘟咕嘟流

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

// now define the gulp task 
gulp.task('jsonResourcesConcat', function gulpTask(){ 
    // build the streams 
    var streams = languages.map(buildJson); 

    // now merge the streams together 
    // see the doc here: https://www.npmjs.com/package/event-stream#merge-stream1streamn-or-merge-streamarray 
    return es.merge(streams); 
}); 

了類似的回答也可以在這裏找到:How to batch similar gulp tasks to reduce code repetition

+0

剛按預期工作,非常感謝:) – Syed