Customizing Source Map Generation in Webpack

How to customize Source Map generation in Webpack, including when to enable it, how to exclude specific files, and important notes about content hashes.

Jun 30, 2024 · 1 min read · 169 Words · -Views -Comments · Programming
Build Tools 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

For production web releases, we enable Source Maps to trace errors back to source code via our RUM platform. Not every bundle needs a Source Map though. How can we customize which files get one?

Enable Source Maps

In Webpack, a simple configuration looks like this:

{
  ...
  devtool: 'source-map',
  ...
}

The downside is that every JS file will get a Source Map. Suppose you want to exclude certain files, e.g., lazily loaded third‑party modules like Monaco Editor. Webpack supports customizing Source Map generation.

Customize Source Maps

Make sure to disable devtool: 'source-map' (set it to false), otherwise the plugin config below won’t take effect.

 devtool: false,
 plugins: [
  new webpack.SourceMapDevToolPlugin({
      filename: '[file].map[query]',
      exclude: [/monaco_/],
    })
 ]

With this configuration, files whose names contain monaco_ will be excluded from Source Map generation.

Note: when bundling JS with content hashes in filenames, enabling Source Maps adds a //# sourceMappingURL=xxx.4ea8e146beed0e49c7c5.js.map comment at the end of the JS file, which changes the file content—and thus its content hash.

Final Thoughts

Done.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover