Source Maps and WordPress

I read a post the other day on Tom McFarlin’s blog, where he talked about some of the hoops he has to jump through in order to debug minified Javascript files in WordPress. I was a bit surprised by the solution, and would like to offer up an alternative that involves leveraging an existing tool created for this exact purpose. Perhaps it’s a tool that people who spend the majority of their time writing server-side code are not even aware of.

Source Maps to the Rescue

Since my day job is a front-end developer, I spend a lot of time writing bug-free code debugging Javascript. It should come as no surprise that debugging minified Javascript is a nightmare, if not downright impossible. But there is hope!

Source maps are a tool that enables you to debug minified Javascript files more easily. They work by mapping minified code back to its non-minified version. You can then debug this non-minified Javascript as per usual.

Source maps don’t affect performance because they are only loaded when the dev tools are opened. Support for them is already enabled in Firefox by default, but you may need to turn them on in Chrome. To do that, open the Settings pane in Chrome’s DevTools. On the General tab, ensure that Enable CSS source maps and Enable JavaScript source maps are checked:

Screenshot of the General tab in the Settings pane of Chrome DevTools that shows how to enable source maps
Enable CSS and Javascript source maps in Chrome DevTools

When debugging with source maps, the non-minified code can be found in the source/js folder of Chrome DevTools:

Screenshot of Chrome DevTools showing how a minified Javascript file can be debugged by using source maps
Debug minified Javascript using source maps

One particularly annoying thing to be aware of is that you can’t inspect variables using their original name. You need to use the name of the minified variable.

Generating a Source Map

If you use Gulp in your WordPress projects, there’s an npm package available called gulp-sourcemaps that will automatically create source maps as part of the build. The following Gulp task minifies Javascript (.js) files and generates source maps (.js.map) for each, and outputs the resulting files to the dist folder:

gulp.task("source", function () {
  return gulp.src(["./src/widget/*.js"])
    .pipe(sourcemaps.init())
    .pipe(uglify())
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest("dist/"));
});

If you use Grunt, grunt-contrib-uglify is a good option, as is grunt-jsmin-sourcemapClosure compiler is another alternative if you’re not using a build system at all.

Hopefully I’ve given someone that Holy crap! moment that I had when I heard about source maps for the first time. Use them wisely!