1
0
Fork 0
mirror of https://github.com/NixOS/nix.dev.git synced 2024-10-18 14:32:43 -04:00
nix.dev/source/guides/recipes/direnv.md
fricklerhandwerk 8afee98203 dissolve the Learning Journey section
This does not yet follow #701, because the change to get there would be
too big. The goal is to keep the table of contents meaningful at all
times and the diff of each pull request manageable.

The packaging tutorial is quite important, so it's not wrong to have it
visible on the front page until we have enough material for a packaging
section.

The sharing dependencies article should really be a very brief guide, but
because that would be quite a big change, it's only moved to the Guides
section for now.
2023-11-02 00:13:32 +01:00

1.6 KiB

(direnv)=

Automatic environment activation with direnv

Instead of manually activating the environment for each project, you can reload a declarative shell every time you enter the project's directory or change the shell.nix inside it.

  1. Make nix-direnv available
  2. Hook it into your shell

For example, write a shell.nix with the following contents:

let
  nixpkgs = fetchTarball "https://github.com/NixOS/nixpkgs/tarball/nixos-22.11";
  pkgs = import nixpkgs { config = {}; overlays = []; };
in

pkgs.mkShell {
  packages = with pkgs; [
    hello
  ];
}

From the top-level directory of your project run:

$ echo "use nix" > .envrc && direnv allow

The next time you launch your terminal and enter the top-level directory of your project, direnv will automatically launch the shell defined in shell.nix

$ cd myproject
$ which hello
/nix/store/1gxz5nfzfnhyxjdyzi04r86sh61y4i00-hello-2.12.1/bin/hello

direnv will also check for changes to the shell.nix file.

Make the following addition:

 let
   nixpkgs = fetchTarball "https://github.com/NixOS/nixpkgs/tarball/nixos-22.11";
   pkgs = import nixpkgs { config = {}; overlays = []; };
 in

 pkgs.mkShell {
   packages = with pkgs; [
     hello
   ];
+
+  shellHook = ''
+    hello
+  '';
 }

The running environment should reload itself after the first interaction (run any command or press Enter).

Hello, world!