ottijp blog

Babelを使っているプロジェクトをgitリポジトリからnpm installする方法

npmレジストリを使わず,gitにある自作のパッケージ(ES2015で書いていてBabelでビルドしている)をnpm installしたい状況があったので,gitリポジトリから直接行う方法を調べました.ローカルディレクトリからのインストールも可能です.

目的が混ざってしまっていますが,binを含むパッケージとしても作成しています.

環境

  • Node.js 0.12
  • npm 2.15
  • OSX 10.11

作ったGitリポジトリ

こちらです.

ottijp/npm-install-from-git-sample

Catクラスの定義と,Tamaという名前のCatインスタンスのsay()を呼ぶだけのbinスクリプトを含んでいます.

src/cat.js
export default class Cat {
  constructor(name) {
    this.name = name
  }
  say() {
    console.log(`${this.name}: meow!!`)
  }
}
bin/npm-install-from-git-sample
#!/usr/bin/env node

var Cat = require('npm-install-from-git-sample').default;

var tama = new Cat('Tama');
tama.say();

使い方

このライブラリに入っているbinのコマンドを実行する場合.

$ npm install https://github.com/ottijp/npm-install-from-git-sample
$ ./node_modules/.bin/npm-install-from-git-sample
Tama: meow!!

ライブラリとして使う場合.

$ npm install https://github.com/ottijp/npm-install-from-git-sample
$ node
> var Cat = require('npm-install-from-git-sample').default;
undefined
> var mike = new Cat('Mike');
undefined
> mike.say();
Mike: meow!!
undefined

ローカルディレクトリからインストールする場合はgitリポジトリのURL部分をパスに変えるだけです.

$ npm install ~/dev/npm-install-from-git-sample

説明

npm installした時のフックスクリプト(postinstallキー)でbabelを使ってビルドしていますが,babelはdevDependenciesに入れておきたいので,postinstall-buildというパッケージを利用しました.

このパッケージがdevDependenciesにあるパッケージをインストールしてビルドし,ビルドが終わったらクリーンアップしてくれます.

package.json
{
...
  "scripts": {
    "build": "babel --presets es2015 -d lib src",
    "postinstall": "postinstall-build lib \"npm run build\""
  },
...
  "dependencies": {
    "postinstall-build": "^2.1.3"
  },
  "devDependencies": {
    "babel-cli": "^6.23.0",
    "babel-preset-es2015": "^6.22.0"
  },
  "bin": {
    "npm-install-from-git-sample": "./bin/npm-install-from-git-sample"
  }
}

注意

私が引っかかった点です.

  • ライブラリとしてのエントリポイント(requireで読み込むもの)はpackage.jsonmainに記述します(参照
  • postinstall-buildの第1引数(今回はlib)のディレクトリが既に存在する場合はビルドがスキップされるので,読み込まれる側のパッケージ開発時にローカルディレクトリからnpm installする時にlibがビルドされているか注意が必要です
  • srcディレクトリはpostinstall-build時に必要になるので,.npmignoreには書かないようにします

ottijp
都内でアプリケーションエンジニアをしています
© 2026, ottijp