Dependencies in the development shell#

When packaging software in default.nix, you’ll want a development environment in shell.nix to enter it conveniently with nix-shell or automatically with direnv.

How to share the package’s dependencies in default.nix with the development environment in shell.nix?

Summary#

Use the inputsFrom attribute to pkgs.mkShellNoCC:

 1# default.nix
 2let
 3  pkgs = import <nixpkgs> {};
 4  build = pkgs.callPackage ./build.nix {};
 5in
 6{
 7  inherit build;
 8  shell = pkgs.mkShellNoCC {
 9    inputsFrom = [ build ];
10  };
11}

Import the shell attribute in shell.nix:

1# shell.nix
2(import ./.).shell

Complete example#

Assume your build is defined in build.nix:

1# build.nix
2{ cowsay, runCommand }:
3runCommand "cowsay-output" { buildInputs = [ cowsay ]; } ''
4  cowsay Hello, Nix! > $out
5''

In this example, cowsay is declared as a build-time dependency using buildInputs.

Further assume your project is defined in default.nix:

1# default.nix
2let
3  nixpkgs = fetchTarball "https://github.com/NixOS/nixpkgs/tarball/nixos-23.11";
4  pkgs = import nixpkgs { config = {}; overlays = []; };
5in
6{
7  build = pkgs.callPackage ./build.nix {};
8}

Add an attribute to default.nix specifying an environment:

 let
   nixpkgs = fetchTarball "https://github.com/NixOS/nixpkgs/tarball/nixos-23.11";
   pkgs = import nixpkgs { config = {}; overlays = []; };
 in
 {
   build = pkgs.callPackage ./build.nix {};
+  shell = pkgs.mkShellNoCC {
+  };
 }

Move the build attribute into the let binding to be able to re-use it. Then take the package’s dependencies into the environment with inputsFrom:

 let
   nixpkgs = fetchTarball "https://github.com/NixOS/nixpkgs/tarball/nixos-23.11";
   pkgs = import nixpkgs { config = {}; overlays = []; };
+  build = pkgs.callPackage ./build.nix {};
 in
 {
-  build = pkgs.callPackage ./build.nix {};
+  inherit build;
   shell = pkgs.mkShellNoCC {
+    inputsFrom = [ build ];
   };
 }

Finally, import the shell attribute in shell.nix:

1# shell.nix
2(import ./.).shell

Check the development environment, it contains the build-time dependency cowsay:

$ nix-shell --pure
[nix-shell]$ cowsay shell.nix

Next steps#