LoginSignup
0
3

More than 3 years have passed since last update.

nodebrewでNode.jsを最新化してnpm install -gし直すルーティンをスクリプトにした

Posted at

nodebrew を使って Node.js のバージョン管理をしている場合、 npm のグローバルパッケージを移動させるのがしんどいです。

ふだんの手順

1. グローバルインストールされている npm のパッケージ一覧をメモする

こんなことしますよね。

$ npm ls -g --depth 0
/Users/kulikala/.nodebrew/node/v14.13.1/lib
├── @aws-amplify/cli@4.29.6
├── @vue/cli@4.5.7
├── aws-cdk@1.67.0
├── firebase-tools@8.12.1
├── nativescript@7.0.10
├── npm@6.14.8
└── npm-check-updates@9.0.4

コピペしてメモを残したりします。

2. nodebrew で最新の Node.js のバージョンをインストールする

$ nodebrew install latest
$ nodebrew use latest

3. 控えておいた npm パッケージたちを再インストールする

$ npm i -g @aws-amplify/cli @vue/cli aws-cdk firebase-tools nativescript npm-check-updates

nodebrew には、 migrate-package というちょうど良さそうなコマンドがありますが、シンボリックリンクで処理してしまうので、ちょっと都合が悪かったりします。
クリーンに新規インストールした方が node_modules フォルダがキレイになるので、自分はいつもこの方法です。

nodebrew migrate-package <version>    Install global NPM packages contained in <version> to current version

4. 古い Node.js のバージョンをサヨナラする

$ nodebrew uninstall <古いversion>
$ nodebrew clean all

ルーティンをスクリプトにした

Bash 使いなので Bash で書きました。
.bash_profile に次の内容を転記しておくと、 update_node コマンドで全てルーティンをやってくれます。

.bash_profile
update_node () {
  check_env () {
    if ! command_exists nodebrew; then
      echo 'This script updates node via nodebrew.' 1>&2
      echo '    Please install nodebrew.' 1>&2
      echo '    https://github.com/hokaccha/nodebrew' 1>&2
      return 1
    fi

    if ! command_exists jq; then
      echo 'This script uses jq as JSON parser.' 1>&2
      echo '    Please install jq.' 1>&2
      echo '    https://stedolan.github.io/jq/' 1>&2
      return 1
    fi
  }

  command_exists () {
    command -v "$@" > /dev/null 2>&1
  }

  get_node_ver () {
    nodebrew ls \
      | grep current: \
      | cut -d ' ' -f 2
  }

  npm_ls_global () {
    npm ls -g --depth 0 --json \
      | jq --raw-output '.dependencies [].from | select(. != null)'
  }

  if ! check_env; then
    return 1
  fi

  echo 'Updating node...'

  local NODE_CURRENT="$(get_node_ver)"

  echo "Current node: ${NODE_CURRENT}"

  local NPM_GLOBAL="$(npm_ls_global)"

  nodebrew install latest
  nodebrew use latest

  local NODE_LATEST="$(get_node_ver)"

  if [ "${NODE_CURRENT}" = "${NODE_LATEST}" ]; then
    echo 'Already up to date.'
    return 0
  fi

  npm i -g ${NPM_GLOBAL}

  nodebrew uninstall "${NODE_CURRENT}"
  nodebrew clean all

  echo
  echo "Node is updated to: ${NODE_LATEST}"
}

nodebrew について

node.jsのversionを管理するためにnodebrewを利用する

0
3
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
0
3