コンテンツにスキップ

npm

npm は Node.js におけるパッケージマネージャーである。

コマンド

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# インストール
$ npm i xxx
# 上記は以下と同義
# npm --save xxx

# 開発用のインストール
$ npm i -D xxx
# 上記は以下と同義
# npm i --save-dev xxx

# アンインストール
$ npm rm xxx

# グローバルにインストール
$ sudo npm i -g xxx

# インストールしているパッケージ一覧
$ npm ls --depth=0

# 古いパッケージ
$ npm outdated -g

# とりあえずプロジェクトを作る
$ npm init -y

# インストール済みパッケージ一覧
$ npm ls
$ npm ls --depth=0

# インストール済みパッケージ一覧(グローバル)
$ npm ls -g
$ npm ls -g --depth=0

# 更新チェック
$ npm outdated

# 更新
$ sudo npm update xxx
$ sudo npm update -g xxx

npm-check-updates

npm-check-updates を使うとパッケージのアップデートを一括で行うことができる。

GitHub - raineorshine/npm-check-updates: Find newer versions of package dependencies than what your package.json allows

1
$ npm i -g npm-check-updates

npm scripts に引数を渡す

${npm_config_変数名}変数名を使うことができる。

package.json
1
2
3
4
5
{
  "scripts": {
    "hello": "echo Hello, ${npm_config_name}!"
  }
}
1
2
3
4
5
6
$ npm run hello -name="Example Name"

> typescript-sandbox@1.0.0 hello
> echo Hello, ${npm_config_name}!

Hello, Example Name!

パッケージの更新がうまくいかないとき

ソースコードの変更をコミットしておく。

rm -rf package-lock.json node_modules/を実行する。

npm iを実行する。

上手くいくことがある。