LoginSignup
5
2

More than 3 years have passed since last update.

【nvm-windows】ディレクトリ毎に Node.js のバージョンを自動で切り替える

Posted at

functions などを書いていると、Node.js のバージョンを切り替えたいことがありますよね。手動でnvm useするのも面倒なので自動化しましょう。

nvm のインストールについては割愛します。

環境

  • Windows 10 Pro
  • Git Bash
  • nvm 1.1.7

.nvmrc

バージョンを切り替えたいディレクトリに.nvmrcを作成し、nvm にインストール済みの Node.js のバージョンを記述します。

14.10.1

~/.bashrc

以下を追記。ディレクトリを移動した際、.nvmrcが存在すれば、.nvmrcに記述されている Node.js のバージョンを変数に格納し、nvm use [変数]を実行しています。

enter_directory() {
     if [[ $PWD == $PREV_PWD ]]; then
       return
     fi

     PREV_PWD=$PWD
     [[ -f ".nvmrc" ]] && current_node_ver=`cat .nvmrc` && nvm use $current_node_ver
}
export PROMPT_COMMAND=enter_directory

やってみる

$ cd ~/project
$ echo "14.10.1" > .nvmrc
$ cd ~
$ nvm use 10.22.0
Now using node v10.22.0 (64-bit)

$ cd ~/project
Now using node v14.10.1 (64-bit)

自動でnvm use 14.10.1が実行されました。

5
2
0

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
5
2