Skip to content

Instantly share code, notes, and snippets.

@alternacrow
Last active July 23, 2023 14:24
Show Gist options
  • Save alternacrow/92fd4983e65c019308fa3e2d17cff0ee to your computer and use it in GitHub Desktop.
Save alternacrow/92fd4983e65c019308fa3e2d17cff0ee to your computer and use it in GitHub Desktop.
pnpm

pnpm

https://pnpm.io/ja/

Performant npmの略。

モチベーション

  1. ディスク容量の節約
  2. インストール速度の向上
  3. フラットでないnode_modulesディレクトリの作成

pnpm は全てのインストールするファイルをContent-addressable store(コンテンツ探索可能なストア)と呼ばれるディレクトリに保存し、Virtual storeであるnode_modules/.pnpmにハードリンクを作成する。
プロジェクトの依存関係にあるパッケージはnode_modulesにシンボリックリンクを作成し、各パッケージの依存関係はnode_modules/.pnpmでシンボリックリンクを作成する。

node_modules
├── foo -> ./.pnpm/foo@1.0.0/node_modules/foo
└── .pnpm
    ├── bar@1.0.0
    │   └── node_modules
    │       ├── bar -> <store>/bar
    │       └── qar -> ../../qar@2.0.0/node_modules/qar
    ├── foo@1.0.0
    │   └── node_modules
    │       ├── foo -> <store>/foo
    │       ├── bar -> ../../bar@1.0.0/node_modules/bar
    │       └── qar -> ../../qar@2.0.0/node_modules/qar
    └── qar@2.0.0
        └── node_modules
            └── qar -> <store>/qar

これよって、プロジェクトの依存関係にないパッケージを import 出来る問題も解消されている。

インストールは、依存関係の解決 → ディレクトリ構造の計算 → 依存関係をリンクするという 3 つのステップで行われ、各パッケージで並列に行うことで高速化されている。

参考

フラットな node_modules が唯一の方法ではありません
https://pnpm.io/ja/blog/2020/05/27/flat-node-modules-is-not-the-only-way

シンボリックリンクを使用した node_modules の構造
https://pnpm.io/ja/symlinked-node-modules-structure

コマンド

scripts の並列実行

https://pnpm.io/ja/cli/run#running-multiple-scripts

デフォルトで scripts 並列実行に対応している。

pnpm run "/<regex>/"

pre/post スクリプト

https://pnpm.io/ja/cli/run#npm-run-%E3%81%A8%E3%81%AE%E9%81%95%E3%81%84

デフォルトでは ユーザー定義の pre/post スクリプトはフックされない。 フックさせたい場合は下記の設定が必要。

# .npmrc
enable-pre-post-scripts=true

設定

engine のバージョン指定

https://pnpm.io/ja/package_json#engines

Node.js や pnpm のバージョンを指定できる。

{
  "engines": {
    "node": ">=10",
    "pnpm": ">=3",
    "npm": "forbidden, use pnpm",
    "yarn": "forbidden, use pnpm"
  }
}

上記だけだと警告が出るだけなので、下記の設定でエラーにすることが出来る。

# .npmrc
engine-strict=true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment