Gatsby: Disable source maps in production


Introduction

Gatsby is static site generator platform based in ReactJS and powered by GraphQL. I’ve been using Gatsby for a while now and most recently used it to rebuild my personal homepage.

One of the things that has come to my attention is that transpiled Javascript source maps are published to production builds by default in V2. It’s nice to be transparent and to publish your source code and share with the software community, but maybe this is an undesirable effect (especially when building commercial websites).

In this post we’ll see how we can configure Gatsby to publish source maps based on the environment for which we’re triggering the build (generate them for development environment and disable source maps in production environment).

Customizing Webpack configuration in Gatsby

Source map generation is controlled through Webpack configuration, more specifically in the devtool option. In a nutshell, what we want to do is modify Gatsby’s Webpack configuration when running the build script in order to disable source maps if the environment is production.

Gatsby offers the possibility to modify Webpack configuration, both for plugins or for your site by adding configurations to the file gatsby-node.js by using the action setWebpackConfig.

Following is the snippet inserted in my gatsby-node.js file:

In line 2 we check if the build mode is 'production' in order to conditionally modify Webpack’s configuration devtool option (remember source maps are enabled by default in Gatsby). In lines 3-5 we override only devtool configuration option, setting it to false to disable source map generation.

It’s important to highlight that the public directory is not cleaned by default when running gatsby build command. If you modified Webpack configuration after an initial build and you didn’t clear the public directory you will still see remaining source maps from previous builds. You would normally add this as a step in your package.json scripts section.

Webpack ReactJS Gatsby

Leave a comment

Your email address will not be published. Required fields are marked *