コンテンツにスキップ

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を実行する。

上手くいくことがある。

モノレポ化

1
2
3
4
5
6
7
$ pip install git-filter-repo
$ git filter-repo --version
a40bce548d2c

$ mkdir web
$ cd web
$ npm init -y
package.json
1
2
3
4
5
6
{
  "name": "web",
  "version": "4.0.0-beta",
  "private": true,
  "workspaces": ["frontend", "backend"]
}

一時ディレクトリで以下を行う。

1
2
3
4
5
$ mkdir ~/temp
$ cd ~/temp
$ git clone /path/to/web-frontend.git
$ cd web-frontend
$ git filter-repo --to-subdirectory-filter frontend

プロジェクトのルートに戻る

1
2
3
4
5
$ git init
$ git remote add frontend ~/temp/web-frontend
$ git fetch frontend
$ git merge frontend/main --allow-unrelated-histories -m "chore: merge frontend into monorepo"
$ git remote remove frontend
1
2
3
4
$ cd ~/temp
$ git clone /path/to/web-backend.git
$ cd web-backend
$ git filter-repo --to-subdirectory-filter backend
1
2
3
4
$ git remote add backend ~/temp/web-backend
$ git fetch backend
$ git merge backend/main --allow-unrelated-histories -m "chore: merge backend into monorepo"
$ git remote remove backend