ZetCode

Gulp source maps

last modified November 15, 2026

In this article we create source maps with Gulp 5. Since Gulp 4 the src and dest functions have built-in support for source maps, so no plugin is needed. We write inline and external maps, inspect a map, put the maps in another directory, switch them off for production, and check with Node.js that an error in a minified bundle points to the original file.

Source maps

A source map is a JSON file that connects every position of a generated file with the position in the original files. Minified code is hard to read, and a stack trace that points to column 3,400 of a single line does not help. A browser or Node.js that finds a map can show the original code instead. The generated file refers to the map with a special comment at its end, //# sourceMappingURL=....

The plugins in the pipeline must support source maps. They receive the map of the file from the stream, update it, and attach the new one. The plugins in this article, gulp-concat, gulp-terser and gulp-clean-css, all do.

Installing the project

We create a project and install Gulp and the three plugins.

$ mkdir gulp-sourcemaps
$ cd gulp-sourcemaps
$ npm init -y
$ npm i -D gulp gulp-terser gulp-concat gulp-clean-css
$ mkdir -p src/js src/css extra

The example project

The scripts are the same as in the Gulp concat tutorial: a formatPrice function, a Product class, and a script that prints a product.

src/js/utils.js
function formatPrice(value) {
    return value.toFixed(2) + ' EUR';
}

The function formats a price.

src/js/models.js
class Product {

    constructor(name, price) {
        this.name = name;
        this.price = price;
    }

    toString() {
        return `${this.name}: ${formatPrice(this.price)}`;
    }
}

The class uses the function in its toString method.

src/js/app.js
const product = new Product('Keyboard', 49.9);
console.log(product.toString());

The entry script creates a product and prints it. A small stylesheet is used for the CSS example.

src/css/style.css
.box {
    color: #ff0000;
    padding: 0px;
}

.box:hover {
    color: #00ff00;
}

The stylesheet has two rules for the .box class.

Inline source maps

To get a map, we pass sourcemaps: true to src, which starts recording the original content, and a value to dest, which decides where the map is written. The true value in dest embeds the map in the bundle as a Base64 encoded data URI.

return src(scripts, { sourcemaps: true })
    .pipe(concat('bundle.min.js'))
    .pipe(terser())
    .pipe(dest('dist/inline', { sourcemaps: true }));

The bundle ends with the sourceMappingURL comment which contains the whole map as a data URI. We print the beginning of the comment. The result is a self-contained file, but its size grows a lot, because the map includes the original sources. Inline maps are handy during development and unsuitable for production.

$ npx gulp inline --silent
$ tail -c 130 dist/inline/bundle.min.js | head -c 90; echo ...
gfVxufVxuIiwiY29uc3QgcHJvZHVjdCA9IG5ldyBQcm9kdWN0KCdLZXlib2FyZCcsIDQ5LjkpO1xuY29uc29sZS5sb...
$ wc -c dist/inline/bundle.min.js
1432 dist/inline/bundle.min.js

External source maps

A string in dest writes an external map into a separate file. The string is the path of the map directory relative to the output directory; the dot means the same directory.

.pipe(dest('dist/external', { sourcemaps: '.' }));

The task writes the bundle and the map. The bundle contains only a short comment with the file name of the map, so the production file stays small, and browsers download the map only when the developer tools are open.

$ npx gulp external --silent
$ ls dist/external
bundle.min.js
bundle.min.js.map
$ tail -c 45 dist/external/bundle.min.js
ng());//# sourceMappingURL=bundle.min.js.map
$ wc -c dist/external/*
 282 dist/external/bundle.min.js
 841 dist/external/bundle.min.js.map
1123 total

The map file

A map is a JSON object. The sources array lists the original files, the sourcesContent array holds their text, names has the identifiers that appear in the mappings, and mappings is a compact encoding of the position pairs. The names of the sources are relative to the base of the glob, here src/js, so the map for the bundle names the three original scripts. We print the parts that can be read.

$ node -p "const m = JSON.parse(require('fs').readFileSync('dist/external/bundle.min.js.map')); [m.version, m.file, m.sources, m.names.length]"
[ 3, 'bundle.min.js', [ 'utils.js', 'models.js', 'app.js' ], 12 ]

Maps for CSS

The built-in support does not depend on the type of file. The CSS task uses the same options and the gulp-clean-css plugin.

return src('src/css/style.css', { sourcemaps: true })
    .pipe(cleanCSS())
    .pipe(dest('dist/css', { sourcemaps: '.' }));

The stylesheet is minified and gets a /*# sourceMappingURL=... */ comment, which is the CSS form of the same reference.

$ npx gulp styles --silent
$ ls dist/css
style.css
style.css.map
$ cat dist/css/style.css
.box{color:red;padding:0}.box:hover{color:#0f0}/*# sourceMappingURL=style.css.map */
$ cat dist/css/style.css.map
{"version":3,"sources":["style.css"],"names":[],"mappings":"AAAA,KACI,MAAO,IACP,QAAS,EAGb,WACI,MAAO","file":"style.css"}

Maps in a separate directory

The string is a path, not only a flag, so we can put the maps into a directory of their own. With '../maps' the map goes next to the output directory, and the comment contains the relative URL. The maps then can be left out of the files that are deployed to the public server.

.pipe(dest('dist/js', { sourcemaps: '../maps' }));

The bundle is in dist/js, the map in dist/maps, and the comment leads from one to the other.

$ npx gulp maps --silent
$ find dist/js dist/maps -type f
dist/js/bundle.min.js
dist/maps/bundle.min.js.map
$ tail -c 50 dist/js/bundle.min.js
));//# sourceMappingURL=../maps/bundle.min.js.map

Maps only in development

The options accept any boolean, so a build for production can skip the maps. The example reads the NODE_ENV variable; with false in both places nothing is tracked or written, and no comment is added. Conditional pipelines are described in more detail in a separate tutorial.

const isProduction = process.env.NODE_ENV === 'production';

return src(scripts, { sourcemaps: !isProduction })
    .pipe(concat('bundle.min.js'))
    .pipe(terser())
    .pipe(dest('dist/conditional', { sourcemaps: !isProduction && '.' }));

In the development run we get the map. With NODE_ENV=production the directory has only the bundle.

$ npx gulp conditional --silent
$ ls dist/conditional
bundle.min.js
bundle.min.js.map
$ rm -r dist/conditional
$ NODE_ENV=production npx gulp conditional --silent
$ ls dist/conditional
bundle.min.js

Using the map

To test that the map works, we add a script that throws an error and build a bundle with it. The file is in the extra directory so that it does not take part in the other builds.

extra/fail.js
function fail(product) {
    throw new Error(`cannot sell ${product.name}`);
}

fail(new Product('Mouse', 19.9));

The script calls fail on its fifth line, and the function throws the error on the second line. The failing task builds the bundle with an external map.

Without a map the stack trace of the minified file shows a single huge line. Node.js reads source maps when we start it with the --enable-source-maps flag. The trace then points to the original lines of fail.js: line 2, where the error is thrown, and line 5, where the function is called. The directory in the path is the one of the map, because the source name in the map is relative; the file does not need to exist there. Browsers do the same in the developer tools.

$ npx gulp failing --silent
$ node --enable-source-maps dist/failing/fail.min.js 2>&1 | grep -E "^Error|^    at |^Keyboard" | head -4
Keyboard: 49.90 EUR
Error: cannot sell Mouse
    at fail (~/Documents/prog/js/gulp-sourcemaps/dist/failing/fail.js:2:1)
    at Object.<anonymous> (~/Documents/prog/js/gulp-sourcemaps/dist/failing/fail.js:5:1)

Source

Gulp src, Gulp dest, Source map on MDN

In this article we have created source maps with the built-in support of Gulp 5: we wrote inline and external maps, inspected a map, moved the maps to another directory, switched them off for production, and used a map to find an error in the original source. See also the Gulp src and dest 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.