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, it is highly encouraged you to contribute back 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
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:
- develop: when running the
gatsby developcommand. Has configuration for hot reloading and CSS injection into page
- develop-html: same as develop but without react-hmre in the babel config for rendering the HTML component.
- build-html: production build static HTML pages
Check webpack.config.js for the source.
Here is an example adding an additional global variable via the
DefinePlugin and the
Instead of writing
import Header from '../../components/header' over and over again you can just 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.
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:
You need this if you want to do things like transpile parts of