Skip to content

Instantly share code, notes, and snippets.

@aispin
Last active November 8, 2024 10:10
Show Gist options
  • Save aispin/0c3fc47b417e93959f9473d1c2f739ff to your computer and use it in GitHub Desktop.
Save aispin/0c3fc47b417e93959f9473d1c2f739ff to your computer and use it in GitHub Desktop.
NodeJS
Tips on using NodeJS

Automatically switch nodejs versions nvm

  1. 安装 nvm

    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.0/install.sh | bash
  2. 创建 .nvmrc 文件:

    echo "22.6.0" > .nvmrc
  3. ~/.zshrc~/.bashrc~/.oh-my-zsh/custom 目录中新建一个nvmrc.zsh文件中添加下面的内容:

    check_nvm_installed() {
      if ! command -v nvm &> /dev/null; then
        return 1
      fi
      return 0
    }
    
    # load the nodejs specified in the .nvmrc
    autoload_nvmrc() {
      if check_nvm_installed; then
        if [ -f .nvmrc ]; then
          nvm use
        fi
      fi
    }
    
    # hook function, will be excuted whenever enterring a dir
    if [ -n "$ZSH_VERSION" ]; then
      # Zsh
      autoload -U add-zsh-hook
      add-zsh-hook chpwd autoload_nvmrc
      autoload_nvmrc
    elif [ -n "$BASH_VERSION" ]; then
      # Bash
      PROMPT_COMMAND="autoload_nvmrc;$PROMPT_COMMAND"
    fi

    或参考:https://github.com/nvm-sh/nvm#zsh

    如果是在~/.oh-my-zsh/custom下创建文件,需要把以下 nvm 初始化的内容放到 ~/.zshrc的顶部:

    export NVM_DIR="$HOME/.nvm"
    [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
    [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion
  4. 重新加载 shell 的配置文件

    source ~/.zshrc  # 如果使用的是 Zsh
    # 或
    source ~/.bashrc  # 如果使用的是 Bash
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment