Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9050

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

$
0
0

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を利用する


Viewing all articles
Browse latest Browse all 9050

Latest Images

Trending Articles