While setting up a build system with webpack 5.1.1 today webpack informed me that since 4.x the API has changed and webpack no longer includes polyfills for Node.js core modules by default, but that I can include one myself by using require.resolve()
to add fallbacks for when these are missing (which they obviously are in non-Node contexts).
So far so good. What was not clear however was why in some of these instructions a trailing slash was put after the name of the module whereas in other cases there was no trailing slash.
Excerpts from the log:
Example without trailing slash:
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
- install 'stream-browserify'
Example with trailing slash:
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
Which brings me to my question: What does a trailing slash in the parameter of require.resolve()
mean?
The idea is the following. buffer
is one of core node modules. If you do require.resolve('buffer')
node module resolution algorithm will find this file lib/buffer.js
. But you want it to actually bypass core module and lookup in node_modules
folder. Adding trailing slash does the trick.
From buffer module docs
To depend on this module explicitly (without browserify), require it like this:
var Buffer = require('buffer/').Buffer // note: the trailing slash is important!
To require this module explicitly, use
require('buffer/')
which tells the node.js module lookup algorithm (also used by browserify) to use the npm module named buffer instead of the node.js core module named buffer!