UPDATE 2021-07-19: I recommend checking “fnm on cd” post and starship.rs as well instead of suggestions in this article.
I am working in company that has many nodejs projects and they are
written with assumption that some older node version might be in
use. Node version is written in .nvmrc
file and you have to
write command nvm use
or fnm use
after you enter project’s
directory. It is really easy to forget that and requires extra
typing every time you open new terminal tab/window because you
need that environment again.
So I have decided to automate that and it is quite easy to do. You need to install direnv (it is available via apt or brew, depending on your OS).
Now let’s create fnm rule for direnv. You will need to add following lines to ~/.config/direnv/direnvrc file:
use_fnm() {
fnm use
}
NOTE: if you are using nvm replace fnm use
to nvm use
. Both
fnm and nvm understand .nvmrc file.
Now create .envrc
near .nvmrc
with string use fnm
.
Next time you will cd into your project fnm use
will be run
automatically for you. You will need to run direnv allow
the
very first time because direnv runs .envrc
commands
automatically only for allowed folders.
But let’s not stop here and do a little bit more.
Many projects
Let assume you have many projects and you don’t want to create
.envrc
for each by hand. We can create them with this simple
fd command:
fd --hidden .nvmrc -x sh -c "echo 'use fnm' > {//}/.envrc"
Feel free to use find
command if you want to install fd :smirk:
Git and .envrc
Now let’ assume your co-workers don’t want to see .envrc
committed to git repository for some reason. In order to solve
that create global ~/.gitconfig
file if you have not done that
yet. Add excludesfile
into it:
[core]
excludesfile = ~/.gitignore_global
And add .envrc
to ~/.gitignore_global
file:
.envrc
That’s it. You will not commit .envrc
accidentally anymore.
Bash and node version
Lastly you might want to see your current node version always as
we are running fnm use
automatically. The solution is to add
following lines to your bash configuration file.
show_node_version() {
node -v
}
PS1='[N:$(show_node_version)]'$PS1
I hope you have found this useful.