Explain Codes LogoExplain Codes Logo

How do I generate sourcemaps when using Babel and Webpack?

javascript
webpack
babel
sourcemaps
Alex KataevbyAlex Kataev·Feb 12, 2025
TLDR

Activate sourcemaps in Webpack with devtool: 'source-map'. In babel-loader options, set sourceMaps: true. Here’s the nutshell config:

module.exports = { devtool: 'source-map', // Here be maps 🗺️ module: { rules: [{ test: /\.js$/, use: { loader: 'babel-loader', options: { sourceMaps: true } // Babel, do the mapping! ⚒️ } }] } };

Fire up Webpack to generate .map files for your JavaScript bundles.

Devtool types: Development vs. production

Development environment:

  • For rapid rebuilds, use eval-cheap-module-source-map.
  • Aids extremely fast debugging.

Production environment:

  • For detailed source maps, set devtool: 'source-map'.
  • Minimizes source maps to reduce output size and cloak source code.

Source maps and Babel-loader

Exclude node_modules:

  • Speed up the build process by excluding node_modules. Babel can enjoy a tea break! ☕
{ test: /\.js$/, exclude: /node_modules/, // Node_modules, you shall not pass! 🧙 use: { loader: 'babel-loader', options: { sourceMaps: true } } }

Balancing rebuilds and source map accuracy

  • Your chosen devtool impacts your rebuild speed and source map precision.
  • Assess the trade-offs and strike a balance to suit your project’s size & complexity.

UglifyJsPlugin configuration

  • When using Webpack 2 or above, make sure sourceMap is enabled in the UglifyJsPlugin.
  • Because everyone enjoys scavenger hunts! 🎁
const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); module.exports = { optimization: { minimizer: [new UglifyJsPlugin({ sourceMap: true })], // Uglify, get mapping! }, // ... }

Environment-specific configuration:

  • Use process.env.NODE_ENV to tweak the sourcemap setting for development or production.
module.exports = { devtool: process.env.NODE_ENV === 'development' ? 'eval-source-map' : 'source-map', // Conditional mapping, cool huh? // ... };

Debug & trace errors with sourcemaps

Sourcemaps FTW!:

  • For valuable development debugging, encourage eval-source-map.
  • High-quality source maps delivered at acceptable build speeds.

Accurate tracing:

  • For top-notch error tracking, sourcemaps are your pals.
  • Error reporting services like Sentry love a good source map!

Advanced sourcemaps

High performance in large-scale projects:

  • Gauge sourcemap's effects on performance.
  • Make an informed choice to strike a balance between debuggability and performance.
  • Test and adapt!

Source code confidentiality:

  • Sourcemaps may expose your source code in production.
  • Keep them locked in your private server or remove after deployment for maximum confidentiality.

Automation in CI/CD pipelines:

  • Integrate sourcemap generation inline for consistent builds.

Granular control:

  • The SourceMapDevToolPlugin is just right if you fancy granular control over sourcemap generation.