Skip to content
MountainPass Blog

Gatsby and Webpack5

nodejs, webpack, gatsby1 min read

- by Nick Grealy and Sam Wei

Background:

webpack5 has breaking changes, which means nodejs polyfills are no longer included by default. They now need to be manually setup - here is how to do it.

You might see an error similar to the following:

console
1Generating development JavaScript bundle failed
2
3Can't resolve 'buffer' in '../yourproject/node_modules/safe-buffer'
4
5If you're trying to use a package make sure that 'buffer' is installed. If you're trying to use a local file make sure that the path is correct.
6
7BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
8This is no longer the case. Verify if you need this module and configure a polyfill for it.
9
10If you want to include a polyfill, you need to:
11 - add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
12 - install 'buffer'
13If you don't want to include a polyfill, you can use an empty module like this:
14 resolve.fallback: { "buffer": false }

Steps to fix

N.B. Include polyfill libraries as required.

1. Install libaries

Run the following commands:

console
1# install ncu
2npm i -g npm-check-updates
3
4# install latest gatsby
5ncu -u gatsby
6
7# install required dependencies
8npm i stream-http https-browserify crypto-browserify stream-browserify os-browserify assert url buffer

2. Add polyfills to webpack

Update the gatsby-node.js file to include the following:

gatsby-node.js
1// has to add all of these due to webpack 5
2const webpack = require('webpack')
3
4exports.onCreateWebpackConfig = ({ actions }) => {
5 actions.setWebpackConfig({
6 resolve: {
7 fallback: {
8 http: require.resolve('stream-http'),
9 https: require.resolve('https-browserify'),
10 crypto: require.resolve('crypto-browserify'),
11 stream: require.resolve('stream-browserify'),
12 os: require.resolve('os-browserify/browser'),
13 assert: require.resolve('assert/'),
14 url: require.resolve('url'),
15 Buffer: [require.resolve('buffer/'), 'Buffer']
16 }
17 },
18 plugins: [
19 new webpack.ProvidePlugin({
20 Buffer: ['buffer', 'Buffer'],
21 process: 'process/browser'
22 })
23 ]
24 })
25}

And that should be it.

© 2021 by MountainPass Blog. All rights reserved.
Theme by LekoArts