— nodejs, webpack, gatsby — 1 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:
1Generating development JavaScript bundle failed2
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 }N.B. Include polyfill libraries as required.
Run the following commands:
1# install ncu2npm i -g npm-check-updates3
4# install latest gatsby5ncu -u gatsby6
7# install required dependencies8npm i stream-http https-browserify crypto-browserify stream-browserify os-browserify assert url bufferUpdate the gatsby-node.js file to include the following:
1//  has to add all of these due to webpack 52const 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.