A better way to manage your projects’ configuration

What’s direnv?

Why would I use direnv?


# debian
apt install direnv
# mac - https://formulae.brew.sh/formula/direnv
brew install direnv
# suse / opensuse
zypper in direnv
# snap - https://snapcraft.io/direnv
snap install direnv
# bash
echo eval "$(direnv hook bash)" >> ~/.bashrc
# zsh
echo eval "$(direnv hook zsh)" >> ~/.zshrc
# fish
echo 'direnv hook fish | source' >> ~/.config/fish/config.fish

Ok, now what …

echo 'export DIRENV_ENV=hello-from-direnv' > .envrc
direnv: error /test-project/.envrc is blocked. Run `direnv allow` to approve its content
direnv allow

Testing direnv with Docker

FROM alpine:3.13ENV EDITOR=viRUN apk add bash \
&& apk add --no-cache -X http://dl-cdn.alpinelinux.org/alpine/edge/testing direnv \
&& echo eval "$(direnv hook bash)" >> ~/.bashrc
docker build --tag direnv-demo .
docker run --interactive --tty direnv-demo bash

Editing direnv files

export EDITOR=idea # to open with Jetbrains IDEAorexport EDITOR="code --wait" # to open with vscode

Utility functions

A real world example

use_nodeenv() {
type nvm >/dev/null 2>&1 || . ~/.nvm/nvm.sh
nvm use "$NODE_VERSION" # you can use install instead of use if you want to dynamically install version if it not exists
use nodeenv 15.5.1
export PORT=3333
export LOG_LEVEL=info
PATH_add bin
direnv: loading /test/.envrc
direnv: using nodeenv 15.5.1
Now using node v15.5.1 (npm v7.3.0)
info 3333

One last note

... other content ....direnv                       


Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store