Dev environments with direnv and Nix
With direnv
you are able to configure development environments for your projects.
What does this mean?
Well, let's say you have two projects that you maintain. One is using a Haskell/Yesod/Purescript and the other one a Haskell/Servant/Elm combination (the used frameworks are not relevant).
The point is, you have different dependencies in each of your project. For instance, one obvious difference is Purescript and Elm. For each you will have a different approach how to compile the code. Furthermore you may have a different environment variables on how you configure the project.
All sounds like it can be handled with nix only, right? Well, yes. But, direnv
is the sherry on the cake. First, it enables us to define environment variables easier, second it can create this development environment for us automatically when we enter the directory of the project. And, we can as well implement a useful file watcher mechanism.
Install and Activate direnv
In this post I assume that you are either running NixOS or you have your nix environment already set up.
To install direnv we can use nix-env like this:
nix-env -iA nixpkgs.direnv
Add direnv to your bash
or zsh
to be evaluated in ~/.bashrc
eval "$(direnv hook bash)" # for bash eval "$(direnv hook zsh)" # for zsh
To use direnv
we can add a .envrc
file to our project and allow direnv
touch .envrc direnv allow
Adding Nix environment to your Project
If you have no shell.nix
file already in your project, you can create a sample shell.nix with the following content:
# save this as shell.nix { pkgs ? import <nixpkgs> {}}: pkgs.mkShell { nativeBuildInputs = [ pkgs.hello ]; }
For linking nix and direnv there is a useful project called nix-direnv which can be installed with nix-env as well:
nix-env -iA nixos.nix-direnv
After this installation we can add nix to direnv within our project:
echo "use nix" >> .envrc
With this Set-up a nix shell
with all defined dependencies will be loaded when you cd
into your project. Happy coding!