I've got the following for my gulpfile:
const gulp = require("gulp");
const sourcemaps = require("gulp-sourcemaps");
const browserify = require("browserify");
const source = require("vinyl-source-stream");
const buffer = require("vinyl-buffer");
const babel = require("babel");
const uglify = require("uglify");
gulp.task("default", function() {
return browserify("src/app.js", {debug: true})
.bundle()
.pipe(source("app.js"))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(babel({presets: ["env"]}))
.pipe(uglify())
.pipe(sourcemaps.write("/src"))
.pipe(glup.dest("dist"));
});
Pretty standard stuff. My src/app.js
contains only the following:
const $ = require("jquery");
console.log($);
Now when I run gulp
and look in the Chrome console, I see the following:
The first app.js
file in this list, located in src/js/app.js
, is my actual source file, containing two lines of code.
The last app.js
file in this list, located in app.js
(no subdirectory), is the compiled and minified version with one line of incomprehensible garbage
The middle one, however, located in src/app.js
, contains the full browserified source before running babel or uglify (the "const" keyword is still present and it's multi-line and entirely readable)
This makes my source map twice as large as it needs to be, as it contains the entire source code of the project twice. Any tips on cleaning it up?
Doing a few quick tests, I've narrowed the issue down to Babel.
When I remove Babel and just run Uglify (modifying app.js
to remove the const
keywords so Uglify doesn't barf on me) I don't get the duplicate code in my source map.
When I remove Uglify and just run Babel, I still get the duplicate code.
For some reason when Babel sees the output from Browserify it seems to treat both the original source maps and the original source file as source code (putting them both in the final source map).
Is there something I need to pass to Babel to fix this?
Although I didn't find a way to get it working with Babel directly, I did find a way to bypass the .pipe(babel())
step:
npm install --save-dev babelify
If you use the Browserify transform instead of using Babel directly, then the source maps are never wrong in the first place:
// Most of the file omitted for brevity. Only new / different stuff shown
const babelify = require("babelify");
browserify("app.js", {debug: true})
.transform(babelify, {presets: ["env"]})
.bundle()
This works as expected and created a source map with only one instance of all code.