70 %
Chris Biscardi

Gatsby Themes, Webpack Loaders, and NPM Packages

Shipping NPM packages is tough, especially for new users. We need to either use build tooling to precompile our code or somehow make the user set up a set of loaders with their build tool of choice.

Note The webpack config below has now been built-in to Gatsby core for themes.

With Gatsby and Themes, we have another option. Since Gatsby Themes have access to the Webpack config in gatsby-node (using the onCreateWebpackConfig lifecycle), they can extend the Webpack config with their own requirements. It looks like this and because Gatsby offers a unified set of APIs we can make some assumptions about the user's environment and it means you don't have to think about how to precompile your code for users deploying to IE10. As a theme author write using either the default Gatsby JS babel config, or use anything else you want, and ship it to users in a way that means they can configure how many polyfills to ship.

* When shipping NPM modules, they typically need to be either
* pre-compiled or the user needs to add bundler config to process the
* files. Gatsby lets us ship the bundler config *with* the theme, so
* we never need a lib-side build step. Since we dont pre-compile the
* theme, this is how we let webpack know how to process files.
exports.onCreateWebpackConfig = ({
}) => {
debug("ensuring Webpack will compile theme code");
module: {
rules: [
test: /\.js$/,
include: path.dirname(
use: [loaders.js()]

If this is interesting to you, check out the relevant code in the themes example repo to explore how this works.