Fixing Node.js Modules Pollyfill Errors in Webpack 5+

Starting with v5, webpack no longer automatically pollyfills core Node.js modules. If you have code that depends on modules such as fs, path, and etc, or you have dependencies that require these module, your code will break when you use or upgrade to web pack 5+. On the one hand, it makes sense not to always include these backend centric modules, but on the other hand, it can quite annoying! Fortunately, it is quite easy to fix.

Solution

Simply install the packages that do the required pollyfill manually under webpack.config.js’s resolve.fallback configs. See the example in webpack’s documentation:

For instance, if you need the fs module for file system accesses, simply:

  1. Install browserify-fs: npm install browserify-fs
  2. Add fs to fallback config:
module.exports = {
//...
resolve: {
fallback: {
fs: require.resolve('browserify-fs'),
},
},
};

Process Module

For the process module, it needs to be handled a bit differently. Uses resolve.alias config instead without installing any package:

module.exports = {
//...
resolve: {
alias: {
process: "process/browser"
}
},
};

Using node-polyfill-webpack-plugin

Alternatively, we can also install node-polyfill-webpack-plugin. This plugin essentially does the aliasing works for us in webpack. It also provides the handy options to choose which modules to include or exclude. However, some modules such as fs are not included, which we still have to import ourselves.

When using node-polyfill-webpack-plugin, you may want to exclude modules that are part of the Web API that browsers already support such as console or Buffer.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store