为什么不能导入或要求 peerDependency,即使它存在于父模块中?

Why can't a peerDependency be imported or required, even when it's present in the parent module?

我正在尝试使用 npm peerDependencies,但似乎没有任何效果像宣传的那样有效。我错过了什么?

设置是,我有两个模块,modplugin,它们都依赖于来自 npm 的外部模块。 mod 声明对 plugin 和外部模块的硬依赖,插件声明对等依赖,以便访问父模块正在使用的版本。

文件如下所示:

~/plugin/package.json:

    {
      "name": "plugin",
      "version": "1.0.0",
      "main": "index.js",
      "peerDependencies": {
        "pad-right": "^0.2.2"
      }
    }

~/plugin/index.js

    var peerDependency = require('pad-right')
    module.exports = 'this is a plugin'

~/mod/package.json:

    {
      "name": "mod",
      "version": "1.0.0",
      "main": "index.js",
      "dependencies": {
        "pad-right": "^0.2.2",
        "plugin": "../plugin"
      }
    }

~/mod/index.js:

    var hardDependency = require('pad-right')
    var plugin = require('plugin')

据我从文档和示例中了解到,我认为这应该是使用对等依赖项的标准方法,并且 运行ning npm install 在任一目录中都不会给出任何错误或警告.

然而,当我在 mod 文件夹中 运行 webpack 时,我得到如下错误:

ERROR in ../plugin/index.js
Module not found: Error: Can't resolve 'pad-right' in '~/plugin'
 @ ../plugin/index.js 1:21-41
 @ ./index.js

这里出了什么问题,webpack 不应该使用来自父 mod 模块的对等依赖来解析 plugin 中的 require 语句吗?

啊,看起来这是一个边缘案例,它只影响通过文件系统在本地相互引用的模块。

解决方案显然是添加如下内容:

    resolve: {
        alias: {
            'pad-right': path.resolve('node_modules', 'pad-right'),
        },
    },

到你的 webpack 配置。 (或者尝试 resolve.symlinks: false,它解决了我发布的最小重现代码中的问题,但没有解决我实际项目中的问题)。

Article about the issue