【问题标题】:npm peerDependencies during development开发过程中的 npm peerDependencies
【发布时间】:2014-09-05 10:56:00
【问题描述】:

设置:

models

  • 跨多个应用程序使用的常见猫鼬模型
  • peerDependencies:“猫鼬”

app

  • 依赖项:“猫鼬”、“模型”
  • 通过app> npm link models与模型链接

问题:

开发models时,需要在node_modules下安装mongoose,否则找不到mongoose。

但是,当在app 下使用models 时,如果猫鼬存在于models 中的node_modules 下,它将使用该副本而不是与app 共享相同的猫鼬实例。

我现在做这项工作的方式是在开发models 时安装猫鼬,然后在app 下使用它时将其删除。我已经查看了parent-require,但这似乎只解决了 npm 链接没有从父级找到包的问题,​​而不是必须删除/安装 node_module 的问题(或者我这样做不正确?)

相关: Sharing a Mongoose instance between multiple NPM packages

【问题讨论】:

    标签: node.js npm


    【解决方案1】:

    对于需要共享实例的模块,我已经开始使用 require.main.require 而不是 require

    例如,require.main.require('mongoose') 将保证只使用顶级 mongoose。

    【讨论】:

    【解决方案2】:

    万一出现错误

    require.main.require is not supported by webpack
    

    ...在模块的根目录中调用npm link <required module>

    例如我对 peerDependency react 有同样的问题。所以我为我的本地模块做了npm link reack,它成功了。

    【讨论】:

      【解决方案3】:

      这是一个您可以使用的模块,用于处理链接的父模块和祖父模块

      /**
       * the original module scope
       */
      const _BASE_MODULE = module;
      
      /**
       * the top level module (fixes nasty peer dependency issues with npm link)
       */
      const _MODULE = topLevelModule();
      
      /**
       * find topmost module scope
       */
      function topLevelModule() {
          let _mod = _BASE_MODULE;
      
          while (_mod.parent) {
              _mod = _mod.parent;
          }
      
          return _mod;
      }
      
      /**
       * cheap way to check if the module is available,
       *
       * @param {string} mod module name
       * @return {boolean}
       * @todo if we need better then we should switch to browserifys resolve package, but thats heavy
       */
      export function isAvailable(mod) {
          try {
              _MODULE.require.resolve(mod);
      
              return true;
          } catch (e) {
              return false;
          }
      }
      
      /**
       * requires a module from the top level scope
       * @param {string } mod module name
       * @return {*}
       */
      export function topLevelRequire(mod) {
          return _MODULE.require(mod);
      }
      

      【讨论】:

        猜你喜欢
        • 2017-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-06
        • 2016-12-28
        • 2019-06-12
        • 2021-05-16
        相关资源
        最近更新 更多