Migrate to Netlify Today

Netlify announces the next evolution of Gatsby Cloud. Learn more

Adding a Custom webpack Config

Before creating custom webpack configuration, check to see if there’s a Gatsby plugin already built that handles your use case in the plugins section. If there’s not yet one and your use case is a general one, consider contributing your plugin to the Gatsby Plugin Library so it’s available to others (including your future self).

To add custom webpack configurations, create (if there’s not one already) a gatsby-node.js file in your root directory. Inside this file, export a function called onCreateWebpackConfig.

When Gatsby creates its webpack config, this function will be called allowing you to modify the default webpack config using webpack-merge.

Gatsby does multiple webpack builds with somewhat different configuration. Gatsby calls each build type a “stage”. The following stages exist:

  1. develop: when running the gatsby develop command. Has configuration for hot reloading and CSS injection into page
  2. develop-html: same as develop but without react-hmre in the babel config for rendering the HTML component.
  3. build-javascript: production JavaScript and CSS build. Creates route JavaScript bundles as well as common chunks for JavaScript and CSS.
  4. build-html: production build static HTML pages

Check webpack.config.js for the source.

There are many plugins in the Gatsby repo using this API to look to for examples e.g. Sass, TypeScript, Glamor, and many more!


Here is an example adding an additional global variable via the DefinePlugin and the less-loader:

Absolute imports

Instead of writing import Header from '../../components/header' over and over again you can write import Header from 'components/header' with absolute imports:

You can always find more information on resolve and other options in the official webpack docs.

Importing non-webpack tools using yarn

Note that using absolute imports only applies to webpack resolutions and will not work for other tools, e.g. ESLint or TypeScript. But if you are using yarn, then the best practice is to set up your imports in package.json as shown below:

Modifying the Babel loader

You need this if you want to do things like transpile parts of node_modules.

Start building today on Netlify!
Edit this page on GitHub
© 2023 Gatsby, Inc.