Colin Witkamp Colin Witkamp - 3 months ago 11
Javascript Question

What does '...paths.js' mean in ' gulp.src([...paths.js, '!gulpfile.babel.js'], { base: '.' }) '?

I have the following gulp task:



// Compile ES6 to ES5 and copy to dist
gulp.task('babel', () =>
gulp.src([...paths.js, '!gulpfile.babel.js'], { base: '.' })
.pipe(plugins.newer('dist'))
.pipe(plugins.sourcemaps.init())
.pipe(plugins.babel())
.pipe(plugins.sourcemaps.write('.', {
includeContent: false,
sourceRoot(file) {
return path.relative(file.path, __dirname);
}
}))
.pipe(gulp.dest('dist'))
);





According to the Gulp Doc(gulp.src) I learnt that gulp.src
emits files matching provided glob or array of globs.

But I can't understand the meaning of '...paths.js' here.
There is no file named with 'paths.js' in the project directory.

Is there anybody who can help me to understand it?

Answer

... in that context is ES2015 (aka "ES6") spread syntax: It takes the content of an iterable (like an array) and spreads it out into discrete elements in the array.

Example:

let a = [1, 2, 3];
let b = [...a, 4, 5];
console.log(b); // 1, 2, 3, 4, 5

So

gulp.src([...paths.js, '!gulpfile.babel.js'], { base: '.' })

...is creating a new array with the contents of paths.js followed by '!gulpfile.babel.js' and passing that array into src. I'm assuming paths.js is an array; if so, in this particular case it could be replaced with concat:

gulp.src(paths.js.concat('!gulpfile.babel.js'), { base: '.' })

You can also use spread syntax in function calls:

function testing(a, b, c) {
  console.log("a = " + a);
  console.log("b = " + b);
  console.log("c = " + c);
}
let x = [1, 2, 3];
testing(...x);  // Shows:
                // a = 1
                // b = 2
                // c = 3