gulp
.
src
(
"es6/**/*.js"
)
.
pipe
(
babel
())
.
pipe
(
gulp
.
dest
(
"dist"
));
// browser source
gulp
.
src
(
"public/es6/**/*.js"
)
.
pipe
(
babel
())
.
pipe
(
gulp
.
dest
(
"public/dist"
));
});
Gulp uses the concept of a pipeline to do its work. We start off by telling Gulp what
files we’re interested in:
src("es6/**/*.js")
. You might be wondering about the
**
;
that’s a wildcard for “any directory, including subdirectories.” So this source filter will
pick up all .js files in es6, and any subdirectories thereof, no matter how deep. Then
we pipe those source files to Babel, which is what transforms them from ES6 to ES5.
The final step is to pipe the compiled ES5 to its destination, the dist directory. Gulp
will preserve the names and directory structure of your source files. For example, the
file es6/a.js will be compiled to dist/a.js, and es6/a/b/c.js will be compiled to dist/a/b/
c.js. We repeat the same process for the files in our public/es6 directory.
We haven’t learned any ES6 yet, but let’s create an ES6 sample file, and verify that our
Gulp configuration is working. Create the file es6/test.js that shows off some of the
new features of ES6 (don’t worry if you don’t understand this file; when you’re done
with this book, you will!):
'use strict'
;
// es6 feature: block-scoped "let" declaration
const
sentences
=
[
{
subject
:
'JavaScript'
,
verb
:
'is'
,
object
:
'great'
},
{
subject
:
'Elephants'
,
verb
:
'are'
,
object
:
'large'
},
];
// es6 feature: object destructuring
function
say
({
subject
,
verb
,
object
}) {
// es6 feature: template strings
console.log(
`
${
subject
}
${
verb
}
${
object
}
`
);
}
// es6 feature: for..of
for
(
let
s
of
sentences
) {
say
(
s
);
}
Now create a copy of this file in public/es6 (you can change the contents of the senten‐
ces array if you want to verify that your files are different). Now type
gulp
. When it’s
done, look in the dist and public/dist directories. You’ll see a test.js file in both places.
Go ahead and look at that file, and note that it differs from its ES6 equivalent.
Now let’s try running the ES6 code directly:
$ node es6/test.js
/home/ethan/lje3/es6/test.js:8
function say({ subject, verb, object }) {
26 | Chapter 2: JavaScript Development Tools