如何在打开新的集成终端 VSCode Mac 时 运行 安装 node.js?

How to run install node.js when opening new integrated terminal VSCode Mac?

我希望每次在 MacOS VSCode 上打开新的集成终端 window 时都能够初始化 Node.js。目前,我每次都使用 "nvm (node version manager)" 来初始化 Node.js。

有什么方法可以更新 settings.json 以便每当我在 VSCode 上为 MacOS 打开新的集成终端 window 时自动执行此操作?

我尝试添加:

"terminal.integrated.shellArgs.osx": [
    "nvm use 10"
]

settings.json,虽然这行不通。

我认为 VSCode 不应该 运行 第一次打开 shell 上的任何东西,因为这正是 .bashrc、[=12= 的作用] 和其他此类文件。

对于我自己的用例,我将此代码段添加到我的 .bashrc(每次我打开一个新的交互式非登录 shell 时都会 运行)

find-up () {
    path=$(pwd)
    while [[ "$path" != "" && ! -e "$path/" ]]; do
        path=${path%/*}
    done
    echo "$path"
}

cdnvm(){
    cd "$@";
    nvm_path=$(find-up .nvmrc | tr -d '[:space:]')

    # 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 .

我居然做了一个PR to the nvm-sh/nvm repository with this snippet and it's now part of their documentation。我会使用那里的版本。

还支持 zsh。如果您使用另一个 shell,您可能必须复制相同的逻辑。