--preserve-symlinks


指示模块加载器在解析和缓存模块时保留符号链接。

默认情况下,当 Node.js 从符号链接到不同磁盘位置的路径加载模块时,Node.js 将取消引用该链接并使用模块的实际磁盘“真实路径”作为既是标识符又是定位其他依赖模块的根路径。 在大多数情况下,这种默认行为是可以接受的。 但是,当使用符号链接的对等依赖项时,如下例所示,如果 moduleA 尝试要求 moduleB 作为对等依赖项,则默认行为会引发异常:

{appDir}
 ├── app
 │   ├── index.js
 │   └── node_modules
 │       ├── moduleA -> {appDir}/moduleA
 │       └── moduleB
 │           ├── index.js
 │           └── package.json
 └── moduleA
     ├── index.js
     └── package.json

但是请注意,使用 --preserve-symlinks 会产生其他副作用。 具体来说,如果这些模块是从依赖树中的多个位置链接的,那么符号链接的原生模块可能无法加载(Node.js 会将它们视为两个单独的模块,并会尝试多次加载该模块,从而导致异常被抛出)。

--preserve-symlinks 标志不适用于允许 node --preserve-symlinks node_module/.bin/<foo> 工作的主模块。 要对主模块应用相同的行为,也请使用 --preserve-symlinks-main

Instructs the module loader to preserve symbolic links when resolving and caching modules.

By default, when Node.js loads a module from a path that is symbolically linked to a different on-disk location, Node.js will dereference the link and use the actual on-disk "real path" of the module as both an identifier and as a root path to locate other dependency modules. In most cases, this default behavior is acceptable. However, when using symbolically linked peer dependencies, as illustrated in the example below, the default behavior causes an exception to be thrown if moduleA attempts to require moduleB as a peer dependency:

{appDir}
 ├── app
 │   ├── index.js
 │   └── node_modules
 │       ├── moduleA -> {appDir}/moduleA
 │       └── moduleB
 │           ├── index.js
 │           └── package.json
 └── moduleA
     ├── index.js
     └── package.json

The --preserve-symlinks command line flag instructs Node.js to use the symlink path for modules as opposed to the real path, allowing symbolically linked peer dependencies to be found.

Note, however, that using --preserve-symlinks can have other side effects. Specifically, symbolically linked native modules can fail to load if those are linked from more than one location in the dependency tree (Node.js would see those as two separate modules and would attempt to load the module multiple times, causing an exception to be thrown).

The --preserve-symlinks flag does not apply to the main module, which allows node --preserve-symlinks node_module/.bin/<foo> to work. To apply the same behavior for the main module, also use --preserve-symlinks-main.