ZetCode

Gulp Babel

last modified November 15, 2026

In this article we transpile modern JavaScript with Gulp 5 and Babel. The gulp-babel plugin and @babel/preset-env turn new syntax into code that older browsers understand, for the browsers that we choose with a list of targets.

Babel in a Gulp build

JavaScript gets new syntax every year: arrow functions, classes, private fields, optional chaining. A browser that does not know a feature fails with a syntax error and the whole script does not run. Babel is a compiler that rewrites new syntax into older syntax. The @babel/preset-env preset decides what to rewrite from the list of target browsers: for old browsers it changes a lot, for the current ones almost nothing. The gulp-babel plugin runs Babel on the files of a stream.

Babel only rewrites syntax. It does not add the missing library functions, such as Promise or Array.prototype.flat; the core-js library provides them and the useBuiltIns option of the preset can add the needed ones. If the targets are the current browsers, you may not need Babel at all, because esbuild, see the Gulp esbuild tutorial, can lower the syntax with its target option. Babel is still the choice when we need its plugins or exact browserslist support.

Installing the project

We create a project and install Gulp, the plugin, the Babel compiler and the preset. The project is an ES module project, so we also set the type field.

$ mkdir gulp-babel
$ cd gulp-babel
$ npm init -y
$ npm pkg set type=module
$ npm i -D gulp gulp-babel @babel/core @babel/preset-env
$ mkdir src

The example project

The source has a lot of modern syntax: an arrow function, the exponent operator, a class with a private field, optional chaining, nullish coalescing and a template literal. We compile it for different targets and compare the results.

src/app.js
const numbers = [1, 2, 3, 4, 5];

const squares = numbers.map(n => n ** 2);

class Counter {
    #count = 0;

    increment() {
        return ++this.#count;
    }
}

const counter = new Counter();
counter.increment();

const user = { name: 'Alice', address: { city: 'Paris' } };
const city = user?.address?.city ?? 'unknown';

console.log(`Squares: ${squares.join(', ')}`);
console.log(`City: ${city}, count: ${counter.increment()}`);

The file has 436 bytes.

The gulpfile

The gulpfile has a helper function, compile, that takes the browser targets and the output directory, and five tasks. The options babelrc: false and configFile: false make the helper ignore configuration files, so the targets given in the code are the only ones.

gulpfile.mjs
import { src, dest } from 'gulp';
import babel from 'gulp-babel';
import { pipeline } from 'node:stream/promises';

function compile(targets, out, options = {}) {

    return src('src/app.js', { sourcemaps: true })
        .pipe(babel({
            babelrc: false,
            configFile: false,
            presets: [['@babel/preset-env', { targets, ...options }]]
        }))
        .pipe(dest(out, { sourcemaps: '.' }));
}

export function legacy() {

    return compile('ie 11', 'dist/legacy');
}

export function modern() {

    return compile('last 2 chrome versions', 'dist/modern');
}

export function node() {

    return compile({ node: '22' }, 'dist/node');
}

export function modules() {

    return src('src/lib.js')
        .pipe(babel({ presets: ['@babel/preset-env'] }))
        .pipe(dest('dist/modules'));
}

export function config() {

    return src('src/app.js')
        .pipe(babel())
        .pipe(dest('dist/config'));
}

export function checked() {

    return pipeline(
        src('src/app.js'),
        babel({ presets: ['@babel/preset-env'] }),
        dest('dist/checked')
    );
}

The plugin is used as babel(options), and the options are the same as in the Babel API. The sourcemaps options of src and dest come from Gulp, see the Gulp source maps tutorial.

Compiling for old browsers

The legacy task uses the target ie 11, a browser that knows only ES5. Babel rewrites the arrow function, the ** operator, the class, the private field, the optional chaining and the template literal; the file needs many helper functions for classes and private fields.

export function legacy() {

    return compile('ie 11', 'dist/legacy');
}

The result is seven times bigger than the source. The beginning of the output shows the helpers, and the end the rewritten code: var instead of const, a function instead of the arrow, and Math.pow instead of **.

$ npx gulp legacy --silent
$ wc -c dist/legacy/app.js
3015 dist/legacy/app.js
$ tail -n 12 dist/legacy/app.js
}();
var counter = new Counter();
counter.increment();
var user = {
  name: 'Alice',
  address: {
    city: 'Paris'
  }
};
var city = (_user$address$city = user === null || user === void 0 || (_user$address = user.address) === null || _user$address === void 0 ? void 0 : _user$address.city) !== null && _user$address$city !== void 0 ? _user$address$city : 'unknown';
console.log("Squares: ".concat(squares.join(', ')));
console.log("City: ".concat(city, ", count: ").concat(counter.increment()));//# sourceMappingURL=app.js.map

Compiling for modern browsers

The modern task targets the last two versions of Chrome, which support all the syntax in our file, so Babel leaves it unchanged. The only difference from the source is the formatting and the source map comment. Targets are written as browserslist queries, such as last 2 chrome versions or > 0.5%.

export function modern() {

    return compile('last 2 chrome versions', 'dist/modern');
}
$ npx gulp modern --silent
$ wc -c dist/modern/app.js
461 dist/modern/app.js
$ head -n 9 dist/modern/app.js
const numbers = [1, 2, 3, 4, 5];
const squares = numbers.map(n => n ** 2);
class Counter {
  #count = 0;
  increment() {
    return ++this.#count;
  }
}
const counter = new Counter();

Targeting Node.js

The targets can also be an object. The node task passes { node: '22' }, which gives output for Node.js 22. The result is the same as for modern Chrome. The sizes of the outputs show how much the targets matter.

export function node() {

    return compile({ node: '22' }, 'dist/node');
}
$ npx gulp node --silent
$ wc -c dist/legacy/app.js dist/modern/app.js dist/node/app.js
3015 dist/legacy/app.js
 461 dist/modern/app.js
 461 dist/node/app.js
3937 total

Configuration files and browserslist

Instead of passing the options in the gulpfile, we can keep them in babel.config.json, which Babel finds itself, and the browsers in a .browserslistrc file, which is also used by other tools such as PostCSS Autoprefixer (see Gulp PostCSS). Then babel() needs no arguments. The configuration file has only the preset; the targets file has a single, old Chrome version.

babel.config.json
{
    "presets": ["@babel/preset-env"]
}
.browserslistrc
chrome 70
export function config() {

    return src('src/app.js')
        .pipe(babel())
        .pipe(dest('dist/config'));
}

Chrome 70 knows classes and arrow functions, but not private fields, optional chaining or nullish coalescing, so only these are rewritten. The class keeps its class syntax; the private field is replaced by a WeakMap and helper functions, and the optional chaining by explicit checks. The output is much closer to the source than the output for Internet Explorer.

$ npx gulp config --silent
$ wc -c dist/config/app.js
1484 dist/config/app.js
$ head -n 3 dist/config/app.js | cut -c 1-100
var _user$address$city, _user$address;
function _classPrivateFieldInitSpec(t, i, a) { _checkPrivateRedeclaration(t, i), i.set(t, a); }
function _checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the
$ grep -n "class Counter" dist/config/app.js
10:class Counter {
$ grep -c "var " dist/config/app.js
3

ES modules

The modules task compiles a file with an export statement. In Babel 8 the preset leaves ES modules as they are, which is what bundlers and modern browsers want. If the output has to be CommonJS, set the modules option of the preset to 'commonjs'. A file that has to run in an old browser has to be bundled, for example with esbuild, after the transpilation.

$ npx gulp modules --silent
$ cat src/lib.js
export const greet = name => `Hello, ${name}!`;
$ cat dist/modules/lib.js
export const greet = name => `Hello, ${name}!`;

Errors

We append an invalid line to app.js. A plain .pipe() chain does not report the syntax error of Babel: the task finishes normally with the exit code 0, and nothing is written to the output. This is the same problem that we met with other plugins in the Gulp error handling tutorial. The checked task uses pipeline from node:stream/promises, which fails and prints the message with the position of the error.

import { pipeline } from 'node:stream/promises';

export function checked() {

    return pipeline(
        src('src/app.js'),
        babel({ presets: ['@babel/preset-env'] }),
        dest('dist/checked')
    );
}

The first output is the plain task, the second one the task with pipeline.

$ npx gulp legacy 2>&1; echo "exit code: $?"
[13:46:49] Using gulpfile ~/Documents/prog/js/gulp-babel/gulpfile.mjs
[13:46:49] Starting 'legacy'...
[13:46:49] Finished 'legacy' after 117 ms
exit code: 0
$ npx gulp checked 2>&1; echo "exit code: $?"
[13:46:49] Using gulpfile ~/Documents/prog/js/gulp-babel/gulpfile.mjs
[13:46:49] Starting 'checked'...
[13:46:49] 'checked' errored after 115 ms
[13:46:49] SyntaxError in plugin "gulp-babel"
Message:
    ~/Documents/prog/js/gulp-babel/src/app.js: Unexpected token (21:6)

  19 | console.log(`Squares: ${squares.join(', ')}`);
  20 | console.log(`City: ${city}, count: ${counter.increment()}`);
> 21 | const = ;
     |       ^
  22 |
exit code: 1

Source

@babel/preset-env, gulp-babel on npm, browserslist

In this article we have transpiled JavaScript with Gulp 5 and Babel: we compiled for old and new browsers, set the targets in code and in a browserslist file, and reported syntax errors with pipeline. See also the Gulp esbuild and Gulp Terser tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Gulp tutorials.