LoginSignup
27
15

More than 5 years have passed since last update.

npm の package.json の bin の意味とパッケージ公開

Posted at

今日は、なんとなく使っていた npm をちょっと深堀してみた。自分のためのメモ。

npm アカウントの用意

npm のサイトに、アカウントを作っておく。ユーザ名とパスワード。

2017-12-14_17h43_14.png

最初のプロジェクトを作成。

npm のパッケージは、git とうまく連携できるようになっている様子。npm init の前に先に github でリポジトリを作っておくのが吉。

TsuyoshiUshio/hello-ushio

で作ってみた。先にローカルにgitリポジトリを作ってから、パッケージを作る。

git init
git remote add origin git@github.com:TsuyoshiUshio/hello-ushio.git
npm init

あとは指示に従って作成。下記のような、package.jsonが出来た。bin の項目のみ追加した。

package.json

{
  "name": "hello-ushio",
  "version": "1.0.0",
  "description": "NPM experiment project",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "bin": {
    "hello-ushio": "index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/TsuyoshiUshio/hello-ushio.git"
  },
  "keywords": [
    "experiment"
  ],
  "author": "Tsuyoshi Ushio",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/TsuyoshiUshio/hello-ushio/issues"
  },
  "homepage": "https://github.com/TsuyoshiUshio/hello-ushio#readme"
}

サンプルのこんな感じのindex.js を作っておく

#! /usr/bin/env node

function main() {
    console.log("Hello ushio!");
}

main();

bin の意味合い

このbin の意味が知りたかった。

  • npm/bin
  • 設定をかいておくと、コマンド名を実際のコードにマップしてくれるらしい。
  "bin": {
    "hello-ushio": "index.js"
  },

今回はリポジトリは package.jsonindex.js だけなので、どこにも、hello-ushio コマンドは書いていない。
実際にこのnpm リポジトリをインポートすると

npm install hello-ushio --save

node_modules の下に .bin ディレクトリが出来て、そのなかに、ファイルが出来ている。

$ ls -a
./  ../  .bin/  hello-ushio/

 ~/Codes/npm/test/node_modules
$ cd .bin

 ~/Codes/npm/test/node_modules/.bin
$ ls
hello-ushio*  hello-ushio.cmd

こんなのが出来ている!ちなみに、linux ベースのOS用のファイルもできます。

hello-ushio.cmd

@IF EXIST "%~dp0\node.exe" (
  "%~dp0\node.exe"  "%~dp0\..\hello-ushio\index.js" %*
) ELSE (
  @SETLOCAL
  @SET PATHEXT=%PATHEXT:;.JS;=;%
  node  "%~dp0\..\hello-ushio\index.js" %*
)

グローバルの方もインストールしてみてみます。

$ npm list -g
C:\Program Files (x86)\Nodist\bin
$ which hello-ushio
/c/Program Files (x86)/Nodist/bin/hello-ushio

global にインストールしたら、bin ディレクトリに同じくできています。

npm パッケージを push する

最後にこのnpm パッケージを公開してみます。

git tag 1.0.0
git push --tags
npm add-user
npm publish

みたいな感じで公開されます。

これは簡単ですね。
なるほどー

27
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
15