Skip to content

fnm で npm をインストール

npm(Node Package Manager)は Node.js と一緒にインストールされます。このガイドでは、fnm を通じて npm を管理する方法を紹介します。

npm と fnm の関係

fnm を使用して Node.js をインストールすると、npm も自動的に含まれます:

bash
# Node.js をインストール(自動的に npm を含む)
fnm install 20

# npm バージョンを確認
npm --version

npm バージョンを確認

bash
# 現在の npm バージョンを表示
npm --version

# Node.js と npm バージョンを表示
node --version
npm --version

異なる Node.js バージョンは異なる npm バージョンに対応します:

Node.jsnpm
20.x10.x
18.x9.x
16.x8.x

npm をアップグレード

npm 自己アップグレードを使用

bash
# 最新バージョンにアップグレード
npm install -g npm@latest

# 特定のバージョンにアップグレード
npm install -g npm@10.2.0

Node.js バージョンを切り替え

Node.js バージョンを切り替えると npm バージョンも切り替わります:

bash
# Node.js 20 に切り替え
fnm use 20
npm --version  # 出力:10.x.x

# Node.js 18 に切り替え
fnm use 18
npm --version  # 出力:9.x.x

npm グローバルパッケージ管理

グローバルインストールパスを表示

bash
npm config get prefix

グローバルパッケージの場所

fnm によって管理される Node.js グローバルパッケージは次の場所にあります:

~/.fnm/node-versions/<version>/installation/lib/node_modules

グローバルパッケージをインストール

bash
# グローバルパッケージをインストール
npm install -g pnpm
npm install -g yarn
npm install -g typescript

# グローバルパッケージを表示
npm list -g --depth=0

Corepack を使用

Corepack は Node.js のパッケージマネージャーマネージャーで、npm、yarn、pnpm を管理できます:

Corepack を有効化

bash
# Node.js インストール時に Corepack を有効化
fnm install 20 --corepack-enabled

# または環境変数を設定
export FNM_COREPACK_ENABLED=true
fnm install 20

Corepack を使用

bash
# Corepack を有効化
corepack enable

# 特定のバージョンの yarn を使用
corepack prepare yarn@stable --activate

# 特定のバージョンの pnpm を使用
corepack prepare pnpm@latest --activate

npm 設定

ミラーを設定

bash
# npm ミラーを設定
npm config set registry https://registry.npmmirror.com

# 現在の設定を表示
npm config list

# デフォルトミラーに戻す
npm config set registry https://registry.npmjs.org

一般的なミラー

ミラーソースURL
npm 公式https://registry.npmjs.org
npmmirrorhttps://registry.npmmirror.com
騰訊雲https://mirrors.cloud.tencent.com/npm/

マルチバージョン npm 管理

npm は Node.js と一緒にインストールされるため、複数の npm バージョンを管理する最良の方法は:

方法 1: Node.js バージョンを切り替え

bash
# 複数の Node.js バージョンをインストール
fnm install 20
fnm install 18

# バージョンを切り替え
fnm use 20  # npm 10.x
fnm use 18  # npm 9.x

方法 2: npm を個別にアップグレード

bash
# 現在の Node.js バージョンで npm をアップグレード
npm install -g npm@latest

よくある問題

npm コマンドが見つからない

bash
# Node.js がインストールされていることを確認
fnm list

# 現在のバージョンを確認
fnm current

# Node.js を再インストール
fnm install 20 --use

グローバルパッケージのインストールに失敗

bash
# npm キャッシュをクリア
npm cache clean --force

# 権限を確認
ls -la ~/.fnm/node-versions/

# 再インストール
npm install -g <package>

npm バージョンが一致しない

bash
# Node.js バージョンを確認
fnm current

# npm をデフォルトバージョンにリセット
fnm uninstall <version>
fnm install <version>

ベストプラクティス

1. package.json engines を使用

プロジェクトに Node.js と npm バージョンを指定:

json
{
  "engines": {
    "node": ">=18.0.0",
    "npm": ">=9.0.0"
  }
}

2. .npmrc ファイルを使用

プロジェクトに .npmrc ファイルを作成:

registry=https://registry.npmmirror.com
save-exact=true

3. パッケージマネージャーをロック

packageManager フィールドを使用:

json
{
  "packageManager": "npm@10.2.0"
}

関連リンク