Direnv: Difference between revisions
Moved from the nix-shell article. (with significant improvements) |
(No difference)
|
Revision as of 15:40, 17 May 2025
Direnv is an automatic environment setup utility, loading the specified project environment automatically when you enter your project directory, and reporting the loaded variables to you.
After installing direnv
from Nixpkgs using your preferred method of installation, you can set up the .envrc
file at the root of your directory. Refer to the Direnv Wiki for some examples.
At the root of your repository, Direnv can start by allowing the recently-created .envrc
file to execute:
$ direnv allow .
direnv: loading .envrc
direnv: using nix
[...]
+SIZE +SOURCE_DATE_EPOCH +STRINGS +STRIP +TEMP +TEMPDIR +TMP +TMPDIR +_PATH +buildInputs +builder +checkPhase +cmakeFlags +configureFlags +doCheck +enableParallelBuilding +name +nativeBuildInputs +out +postCheck +preCheck +preConfigure +propagatedBuildInputs +propagatedNativeBuildInputs +shell +src +stdenv +system +testInputs +version ~PATH
.envrc
file unless explicitly authorised. As these files run arbitrary code in your computer, it is a good idea to review the .envrc
files from remote repositories before running direnv allow
.
Once Direnv detects that the current working directory is no longer inside the repository with a .envrc
file, it will automatically unload the environment:
$ cd ..
direnv: unloading
State
Direnv stores files in $XDG_DATA_HOME/direnv
. It contains the information required to persist all allowed and denied .envrc
files across the filesystem.
Keeping that directory means that an .envrc
file only needs to be allowed once in order to run automatically.
Configuring on NixOS
There is a NixOS Module for Direnv (and nix-direnv
) which automatically sets everything up in a given NixOS machine. The following line of code is everything that's necessary for NixOS to automatically install and hook Direnv to the available shells in the system:
{
programs.direnv.enable = true;
}
$ nixos-rebuild switch --sudo
Troubleshooting
Hooking Shells
Depending on the shell you are using, you need to add a line in your shell configuration file. See the Hook section of the Direnv Documentation for more information.
Setting Direnv up using the NixOS module should do this by default.
See Also
- direnv.net.
- The Direnv Wiki.