[Node.js] プライベート NPM モジュールを任意の package.json で指定する

2014.08.08

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

車輪開発大好きおたいがです。こんにちは。(挨拶)

Node.js のアプリケーション開発において、以下のような構造があると仮定します。複数のアプリケーションディレクトリ (app_1, app_2, app_3) と、各アプリケーションから参照できる共通モジュールディレクトリ (common) の例です。( 各ディレクトリはそれぞれ Git リポジトリにて管理されているものとします )

├─ common
├─ app_1
├─ app_2
├─ app_3

このとき上記 common の内容が Java の JAR ファイルや、Flash の SWC のように圧縮できたり、各アプリケーションプロジェクトから参照できたりすれば楽なのですが、そのようなことはできないので、common をプライベート NPM モジュールにして、各アプリケーションの package.json の dependencies に指定することで依存性を保つことにしました。

プライベート NPM モジュール

$ npm init

にて package.json の雛形が生成できますが、それに下記 1 行を加えます。

"private": "true"

package.json の例

{
  "private": "true",
  "name": "common",
  "version": "0.0.1",
  "description": "test common repository.",
  "main": "index.js",
  "author": {
    "name": "taiga"
  },
  "dependencies": {
  }
}

各アプリケーションの package.json

以下のように、各アプリケーションの package.json の dependencies に共通モジュールのリポジトリを指定します。( Github 上のプライベートリポジトリを指定する例です )

{
  "name": "app_1",
  "version": "0.0.1",
  "description": "test app",
  "author": "taiga",
  "dependencies": {
    "common": "git+ssh://git@github.com:myaccount/common.git"
  }
}

記述後

$ npm install

と入力することで、各アプリケーションディレクトリの node_modules フォルダに common モジュールがインストールされます。

依存性の Git URL 参照の種類

本記事を書くまで知らなかったのですが、これだけあります。

npm.org の package.json ドキュメント ( https://www.npmjs.org/doc/files/package.json.html#urls-as-dependencies ) より

git://github.com/user/project.git#commit-ish
git+ssh://user@hostname:project.git#commit-ish
git+ssh://user@hostname/project.git#commit-ish
git+http://user@hostname/project/blah.git#commit-ish
git+https://user@hostname/project/blah.git#commit-ish

commit-ish は、タグや SHA-1 ハッシュ値など。未指定の場合は master を参照します。

.ssh/config の設定

オマケ程度の情報ですが、Github 用の設定は以下のような感じで動いてます。

Host github-private.github.com
  User git
  HostName github.com
  PreferredAuthentications publickey
  IdentityFile ~/.ssh/github-private_rsa

参考

node.js - How to install a private NPM module without my own registry? - Stack Overflow
http://stackoverflow.com/questions/10386310/how-to-install-a-private-npm-module-without-my-own-registry