Skip to content

Instantly share code, notes, and snippets.

@mamboer
Last active August 22, 2024 14:54
Show Gist options
  • Save mamboer/0c3fc47b417e93959f9473d1c2f739ff to your computer and use it in GitHub Desktop.
Save mamboer/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文件中添加下面的内容:

    # 自动加载 .nvmrc 中的 Node.js 版本
    autoload_nvmrc() {
      if [ -f .nvmrc ]; then
        nvm use
      fi
    }
    
    # 钩子函数,在每次进入目录时调用
    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
  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