Run Terminal Faster Using Lazy Loading

I ran into a problem when VS Code would open on startup and after I logged into my OS. I would get a peculiar error on the bottom right-hand side of the application:

Unable to resolve your shell environment in a reasonable time. Please review your shell configuration.

Additionally, I would get a few related Terminal output lines from within VS Code and have to restart that instance. I ended up using lazy loading to fix the problem. Here are the steps you can use.

Solution

1. Identify default terminal settings that are running at runtime.

Example

I use Z shell with Oh My Zsh to reskin my OS Terminal locally. As a result, I know that each Terminal instance is using the “~/.zshrc” file.

I can validate and/or manually set VS Code to use this by going to “Settings (UI) > Terminal > Integrated > Default Profile”.

Note:

You can also override this UI setting within “settings.json” if “terminal.integrated.shell.[linux/osx/windows]” is already set.

2. Identify any shells that might be taking too long.

Example

The root cause of this error for me was “nvm / npm”. On startup, the Terminal within VS Code would take too long to load because npm was being set up every time a new instance or tab was opened.

Oftentimes, “npm” will be automatically added into “.zshrc” and look something like this:

export NVM_DIR="~/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"

3. Where available, use lazy loading for shells.

Since I don’t use “nvm” regularly, it doesn’t make sense to run it every time a new Terminal instance is started. Lazy loading of “nvm”  makes more sense here.

If you’re using Z Shell, then there’s a plugin that’ll do this for you. However, you can also do this manually by following this solution I found on StackOverflow.

nvm-zsh Plugin Implementation

Here’s how to implement with the plugin:

export NVM_LAZY_LOAD="true"
plugins=(zsh-nvm)

Manual Implementation

And here’s the code for manual implementation:

lazynvm() {
  unset -f nvm node npm
  export NVM_DIR=”~/.nvm”
  [ -s “$NVM_DIR/nvm.sh” ] && . “$NVM_DIR/nvm.sh”
}

nvm() {
  lazynvm
  nvm $@
}

node() {
  lazynvm
  node $@
}

npm() {
  lazynvm
  npm $@
}

Lazy Loading for a Speedier Startup

Using the above steps, you should be on your way to a speedier startup! I hope you learned a little more about terminals and VS Code in the process, too.