首页 文章

如何将本地模块指定为npm包依赖项

提问于
浏览
151

我有一个应用程序,它对依赖项下的package.json文件中指定的第三方模块(例如'express')具有通常的依赖关系 . 例如 .

"express"     : "3.1.1"

我想模块化地构建我自己的代码,并且有一组本地(意思是我当前在文件系统上)的模块由package.json安装 . 我知道我可以通过运行来安装本地模块:

npm install path/to/mymodule

但是,我不知道如何通过package.json依赖项结构实现这一点 . 在这个命令中使用 --save 选项只是将 "mymodule": "0.0.0" 放入我的package.json(本地看起来不是't reference the filepath location). If i then remove the installed version from node_modules, and try to re-install from the package.json, it fails (because it looks for 626678 in the central registry, and doesn') .

我确信这是一种告诉 "dependencies": {} 结构的方法,我希望它从文件系统路径安装,但不知道如何 .

还有其他人有这个问题吗?谢谢 .

5 回答

  • 34
  • 221

    从NPM 2.0.0开始,本机支持导入本地依赖项 . 这是documented by danilopopeye in response to a similar question . 我've copied his response here to help anyone needing to find the correct answer, as this question ranks very highly in Google'的搜索结果 .

    此功能是在npm版本2.0.0中实现的 . 例如: {
    “名字”:“巴兹”,
    “依赖”:{
    “bar”:“file:../ foo / bar”
    }
    }
    以下任何路径也有效:../ foo / bar
    〜/富/酒吧
    ./foo/bar
    /富/酒吧

  • 1

    我最终找不到一个简洁的方法所以我去创建一个名为 local_modules 的目录,然后在脚本 - > preinstall中将这个bashscript添加到package.json中

    #!/bin/sh
    for i in $(find ./local_modules -type d -maxdepth 1) ; do
        packageJson="${i}/package.json"
        if [ -f "${packageJson}" ]; then
            echo "installing ${i}..."
            npm install "${i}"
        fi
    done
    
  • 8

    在使用 npm link 命令(建议本地模块的解决方案而不将它们发布到注册表或在node_modules文件夹中维护单独的副本)后,我努力了解,我构建了一个小的npm模块来帮助解决这个问题 .

    该修复程序需要 two easy steps .

    第一:

    npm install lib-manager --save-dev
    

    其次,将其添加到您的 package.json

    {  
      "name": "yourModuleName",  
      // ...
      "scripts": {
        "postinstall": "./node_modules/.bin/local-link"
      }
    }
    

    更多详情,请致电https://www.npmjs.com/package/lib-manager . 希望它可以帮到某人 .

  • 2

    如果可以简单地将node_modules中预装的模块与其他文件一起发布,则可以这样做:

    // ./node_modules/foo/package.json
    { 
      "name":"foo",
      "version":"0.0.1",
      "main":"index.js"
    }
    
    // ./package.json
    ...
    "dependencies": {
      "foo":"0.0.1",
      "bar":"*"
    }
    
    // ./app.js
    var foo = require('foo');
    

    您可能还希望将模块存储在git上并告诉您的父包.json从git安装依赖项:https://npmjs.org/doc/json.html#Git-URLs-as-Dependencies

相关问题