javascriptsvggulpgulp-4svg-sprite

Create a for loop for several file names in a Gulp.js 4 function


I'm currently trying to use one single svg sprite per page, so that it only loads the necessary svg's for each separate page. Is currently working, but I want to create an array so that the task get's called for N pages that I want.

I currently have this structure in gulpfile.js (vers 4):

var autoprefixer = require('autoprefixer'),
    browsersync = require('browser-sync').create(),
    cssnano = require('cssnano'),
    sourcemaps = require('gulp-sourcemaps'),
    del = require('del'),
    gulp = require('gulp'),
    imagemin = require('gulp-imagemin'),
    newer = require('gulp-newer'),
    plumber = require('gulp-plumber'),
    postcss = require('gulp-postcss'),
    rename = require('gulp-rename'),
    sass = require('gulp-sass'),
    svgSprite = require('gulp-svg-sprite');

//Create SVG's into one single image file
function svgs(){
    return gulp
        .src('app/images/src/pageName/*')
        .pipe(svgSprite({
           shape: {
               spacing: {
                   padding: 5
               }
           },
           mode: {
               css: {
                   dest: './',
                   layout: 'diagonal',
                   sprite: 'images/dist/pageName/sprite.svg',
                   bust: false,
                   render: {
                       scss: {
                           dest: 'sass/modules/sprites/_pageName.scss',
                           template: 'app/sass/modules/sprites/_pageNameTemplate.scss'
                       }
                   }
               }
           },
           variables: {
               mapname: 'icons'
           }
       }))
       .pipe(gulp.dest('app/'));
}

exports.svgs = svgs;

The idea is to create an array with the page names and do a for loop:

    var pages = ['page1', 'page2',...];

    function svgs(){
        for (var i = 0; i < pages.length; i++) {

            return gulp
                 .src('app/images/src/' + pages[i] + '/*').........
    }

and then in the console just call the task, but the return only does it for one iteration, anyone have had this before?

Thanks !


Solution

  • Try glob.sync it returns an array:

    const glob = require('glob');
    
    const pageArray = glob.sync('path/to/your/*.pages');
    
    function svgs(done)  {
    
      pageArray.forEach( page => {
        return gulp.src(page)
          ...
      };
      done();
    }