require.resolve() 参数中的尾部斜线是什么意思?
What does a trailing slash in the parameter of require.resolve() mean?
今天在使用 webpack 5.1.1 设置构建系统时,webpack 通知我自从 4.x 以来,API 已经更改,webpack 不再包含 Node.js 核心模块的 polyfills默认情况下,但我可以通过使用 require.resolve()
来添加自己的一个,以便在这些缺失时添加回退(它们显然在非节点上下文中)。
到目前为止一切顺利。然而,不清楚的是,为什么在其中一些指令中,模块名称后面有一个尾部斜线,而在其他情况下没有尾部斜线。
日志摘录:
没有尾部斜杠的示例:
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
- install 'stream-browserify'
带有尾部斜杠的示例:
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
这让我想到了我的问题:require.resolve()
参数中的尾部斜线是什么意思?
思路如下。 buffer
是核心节点模块之一。如果您执行 require.resolve('buffer')
节点模块解析算法将找到此文件 lib/buffer.js
。但是您希望它实际上绕过核心模块并在 node_modules
文件夹中查找。添加尾部斜杠就可以了。
来自缓冲模块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!
今天在使用 webpack 5.1.1 设置构建系统时,webpack 通知我自从 4.x 以来,API 已经更改,webpack 不再包含 Node.js 核心模块的 polyfills默认情况下,但我可以通过使用 require.resolve()
来添加自己的一个,以便在这些缺失时添加回退(它们显然在非节点上下文中)。
到目前为止一切顺利。然而,不清楚的是,为什么在其中一些指令中,模块名称后面有一个尾部斜线,而在其他情况下没有尾部斜线。
日志摘录:
没有尾部斜杠的示例:
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
- install 'stream-browserify'
带有尾部斜杠的示例:
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
这让我想到了我的问题:require.resolve()
参数中的尾部斜线是什么意思?
思路如下。 buffer
是核心节点模块之一。如果您执行 require.resolve('buffer')
节点模块解析算法将找到此文件 lib/buffer.js
。但是您希望它实际上绕过核心模块并在 node_modules
文件夹中查找。添加尾部斜杠就可以了。
来自缓冲模块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!