天天看點

Node多版本管理工具NVM

nvm Node Version Manager Vue:從單頁面到工程化項目

切換Node版本

$ nvm list
        v8.17.0
->      v10.16.0
        v12.22.6
        system
         
$ nvm use 12.22.6
Now using node v12.22.6 (npm v6.14.15)      

使用

.nvmrc

在目錄下建立檔案

.nvmrc

, 指定node的版本

$ echo '12.22.6' > .nvmrc      
$ nvm use
Now using node v12.22.6 (npm v6.14.15)      

自動調用

nvm use

MacOS中在

~/.bash_profile

檔案中添加一下代碼段:

添加如下代碼

## Automatically call nvm use
cdnvm() {
    command cd "$@";
    nvm_path=$(nvm_find_up .nvmrc | tr -d '\n')

    # If there are no .nvmrc file, use the default nvm version
    if [[ ! $nvm_path = *[^[:space:]]* ]]; then

        declare default_version;
        default_version=$(nvm version default);

        # If there is no default version, set it to `node`
        # This will use the latest version on your machine
        if [[ $default_version == "N/A" ]]; then
            nvm alias default node;
            default_version=$(nvm version default);
        fi

        # If the current version is not the default version, set it to use the default version
        if [[ $(nvm current) != "$default_version" ]]; then
            nvm use default;
        fi

        elif [[ -s $nvm_path/.nvmrc && -r $nvm_path/.nvmrc ]]; then
        declare nvm_version
        nvm_version=$(<"$nvm_path"/.nvmrc)

        declare locally_resolved_nvm_version
        # `nvm ls` will check all locally-available versions
        # If there are multiple matching versions, take the latest one
        # Remove the `->` and `*` characters and spaces
        # `locally_resolved_nvm_version` will be `N/A` if no local versions are found
        locally_resolved_nvm_version=$(nvm ls --no-colors "$nvm_version" | tail -1 | tr -d '\->*' | tr -d '[:space:]')

        # If it is not already installed, install it
        # `nvm install` will implicitly use the newly-installed version
        if [[ "$locally_resolved_nvm_version" == "N/A" ]]; then
            nvm install "$nvm_version";
        elif [[ $(nvm current) != "$locally_resolved_nvm_version" ]]; then
            nvm use "$nvm_version";
        fi
    fi
}
alias cd='cdnvm'
cd "$PWD"
      

添加指令

$ vim ~/.bash_profile

# 添加完後讓其生效
$ source ~/.bash_profile      

每次進入目錄後,就會自動切換到指定的Node版本了

Now using node v12.22.6 (npm v6.14.15)      

參考

https://github.com/nvm-sh/nvm#bash

繼續閱讀