Quick: ES6 gulpfile using Gulp 4 with Babel

By default Gulp does not support modern javascript features such as import statements, consts and lets. In this quick post I try to describe how to set up Gulp 4 to allow for a modern gulpfile.

This post assumes you have already installed Gulp 4 as a dev dependency, my other post describes how in the Setting up Gulp4 section.

Install and add Babel to package

First you will have to install babel dev dependencies

$ npm install --save-dev @babel/core @babel/register @babel/preset-env

After which you should add the following to your package.json file

"babel": {
	"presets": ["@babel/env"]
}

Rename gulpfile

Last important thing you will have to do is to rename your gulpfile.js to gulpfile.babel.js, and you’re set!

Example gulpfile and usage

This is an example of a gulpfile.babel.js using import statements, consts and using exports to expose a task.

// import gulp
import gulp from "gulp";

// define functions
const hello = (done) => {
	console.log("Hello");
	done();
}

const world = (done) => {
	console.log("World!");
	done();
}

// Expose helloworld series task
exports.helloworld = gulp.series(hello, world);

And usage

$ gulp helloworld

[17:00:45] Requiring external module @babel/register
[17:00:47] Using gulpfile /mnt/c/www/gulp-tutorial/gulpfile.babel.js
[17:00:47] Starting 'helloworld'...
[17:00:47] Starting 'hello'...
Hello
[17:00:47] Finished 'hello' after 1.72 ms
[17:00:47] Starting 'world'...
World!
[17:00:47] Finished 'world' after 852 μs
[17:00:47] Finished 'helloworld' after 7.64 ms

Related articles