Making Sense of Your Bundle with Webpack Sourcemaps
ICYMI: Tomorrow I'll be giving a 1-hour webinar called "Understanding Webpack". There are currently 80+ people registered to attend. Want to be among them?
You generate sourcemaps for your build by specifying a
devtool value in your Webpack config file. Webpack offers a dizzying array of options, the reason being that they are actually presets that proxy to more fine-grained configurations of the
SourceMapDevToolPlugin. The main considerations are speed of build and rebuild, fidelity to your original source code, and privacy in production. More on this last point in a moment.
When you run Webpack in development mode, it uses the "eval" sourcemapping option by default. This embeds the sourcemaps right into your bundles. If you open your browser dev tools and open the sources tab, you'll see not only the bundle files but the original source files alongside them.
Well actually, you'll see something that sort of resembles your source code, but is wrapped in a bunch of Webpack module-loading boilerplate. For development, I recommend instead specifying
devtool: eval-source-map. It takes a little longer to generate the sourcemaps, but the result is line-for-line fidelity to your original source. Well worth it in my opinion.
If you run a build in production mode (
webpack --mode production), the default is not to generate sourcemaps at all. That might be ok for now, but eventually you're going to need to know the path back to whatever is throwing those pesky errors in production. A good starting option here is
devtool: source-map. This produces the same fidelity output as
eval-source-map, but extracts them to separate files so that they are not downloaded by your end users. They are not loaded until requested through the browser devtools.
I mentioned earlier that one consideration for sourcemaps is privacy in production. In a business setting, you often don't want to share your source code with the world for anyone to download. By keeping them as separate files, you can put them behind authentication, or even remove them from your production servers altogether and upload them to a separate error reporting service, such as Sentry.
Tomorrow, I'll finish up this series on Webpack by showing you how to compose and cascade your configuration files so that they don't become sprawling, monolithic beasts.