4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

git checkoutのたびにnode_modulesを再構築しなくて良くする

Last updated at Posted at 2019-03-28

動機

node_modules は .git 管理外なので git のブランチ移動するたびに再構築しないと行けないが、yarn install に時間がかかりすぎる。

解決方法

git hook の post-checkout で node_modules をキャッシュしたりキャッシュから復元したりする。

hooks を設定したいプロジェクトの .git/hooks ディレクトリに post-checkout ファイルを作成する(無いなら勝手に作ってよい)。

post-checkout
#!/usr/bin/env bash

echo "[cache-node_modules] START"

BRANCH_FROM=`git reflog show -q | head -n1 | awk '$3 == "checkout:" && $4 == "moving" {print $6}'`
BRANCH_TO=`git reflog show -q | head -n1 | awk '$3 == "checkout:" && $4 == "moving" {print $8}'`
BRANCH_FROM_CACHE_NAME=".node_modules_${BRANCH_FROM}"
BRANCH_TO_CACHE_NAME=".node_modules_${BRANCH_TO}"

if [ -d "node_modules" ]; then
	echo "[cache-node_modules] Cache node_modules to ${BRANCH_FROM_CACHE_NAME}"
	mv node_modules ${BRANCH_FROM_CACHE_NAME}
fi

if [ -d "${BRANCH_TO_CACHE_NAME}" ]; then
	echo "[cache-node_modules] Restore node_modules from cache."
	mv ${BRANCH_TO_CACHE_NAME} node_modules
fi

echo "[cache-node_modules] Refresh node_modules"
yarn

echo "[cache-node_modules] DONE"

キャッシュは .node_modules_ブランチ名 に保存されるので、~/.gitignore.node_modules* を追加しておく

これで git checkout するたびに checkout 前の node_modules をキャッシュし、checkout 後の node_modules のキャッシュを復元してくれる。
復元後に yarn install をすることで cache が使えているか確認もしている。

移動前/移動後のブランチ名取ってくるところが怪しい動きするかも知れないです。

4
1
1

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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?