Webpack 4 automatically polyfilled many Node APIs in the browser. This was not a great system, because it could lead to surprisingly giant libraries getting pulled into your app by accident, and it gave you no control over the exact versions of the polyfills you were using.
So Webpack 5 removed this functionality. That means you need to make changes if you were relying on those polyfills. This is a quick reference for how to replace the most common patterns.
For each automatically-polyfilled node package name on the left, this shows the name of the NPM package that was used to polyfill it on the right. Under webpack 5 you can manually install these packages and use them via resolve.fallback
.
List taken from here.
{
assert: "assert/",
buffer: "buffer/",
console: "console-browserify",
constants: "constants-browserify",
crypto: "crypto-browserify",
domain: "domain-browser",
events: "events/",
http: "stream-http",
https: "https-browserify",
os: "os-browserify/browser",
path: "path-browserify",
punycode: "punycode/",
process: "process/browser",
querystring: "querystring-es3",
stream: "stream-browserify",
_stream_duplex: "readable-stream/duplex",
_stream_passthrough: "readable-stream/passthrough",
_stream_readable: "readable-stream/readable",
_stream_transform: "readable-stream/transform",
_stream_writable: "readable-stream/writable",
string_decoder: "string_decoder/",
sys: "util/",
timers: "timers-browserify",
tty: "tty-browserify",
url: "url/",
util: "util/",
vm: "vm-browserify",
zlib: "browserify-zlib"
}
Before:
{
node: {
// provide a polyfill for "path"
path: true
}
}
After:
{
resolve: {
fallback: {
// make sure you `npm install path-browserify` to use this
path: require.resolve('path-browserify')
}
}
}
Before:
{
node: {
// provide an empty implementation of the "fs" module
fs: false
}
}
After:
{
resolve: {
fallback: {
fs: false
}
}
}
Three cheap and common Node global variables are still supported directly via webpack's node
option:
{
node: {
// provides the global variable named "global"
global: true,
// provide __filename and __dirname global variables
__filename: true,
__dirname: true,
}
}
Other globals like Buffer
will need to be handled directly via ProvidePlugin
or DefinePlugin
. For example, to get the Buffer
global variable you can use the buffer
NPM package like:
import webpack from 'webpack';
module.exports = {
plugins: [
new webpack.ProvidePlugin({
// you must `npm install buffer` to use this.
Buffer: ['buffer', 'Buffer']
})
]
}
Alternatively, to replace a global variable directly with a snippet of code, you can use DefinePlugin
. For example, if you want to replace process.env.THING
with false
you can say:
import webpack from 'webpack';
module.exports = {
plugins: [
new webpack.DefinePlugin({
'process.env.THING: 'false'
})
]
}
Any example with ESM, like webpack.config.mjs?