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/sharing-dependencies.md
Aaron Honeycutt 58b5a525c2
update examples to latest release of 23.11 (#913)
update examples to latest release of 23.11

Co-authored-by: Henrik <i97henka@gmail.com>
Co-authored-by: Silvan Mosberger <github@infinisil.com>
2024-02-27 02:48:44 +01:00

113 lines
2.6 KiB
Markdown

(sharing-dependencies)=
# Dependencies in the development shell
When [packaging software in `default.nix`](packaging-existing-software), you'll want a [development environment in `shell.nix`](declarative-reproducible-envs) to enter it conveniently with `nix-shell` or [automatically with `direnv`](./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`](https://nixos.org/manual/nixpkgs/stable/#sec-pkgs-mkShell-attributes):
```nix
# default.nix
let
pkgs = import <nixpkgs> {};
build = pkgs.callpackage ./build.nix {};
in
{
inherit build;
shell = pkgs.mkShellNoCC {
inputsFrom = [ build ];
};
}
```
Import the `shell` attribute in `shell.nix`:
```nix
# shell.nix
(import ./.).shell
```
## Complete example
Assume your build is defined in `build.nix`:
```nix
# build.nix
{ cowsay, runCommand }:
runCommand "cowsay-output" { buildInputs = [ cowsay ]; } ''
cowsay Hello, Nix! > $out
''
```
In this example, `cowsay` is declared as a build-time dependency using `buildInputs`.
Further assume your project is defined in `default.nix`:
```nix
# default.nix
let
nixpkgs = fetchTarball "https://github.com/NixOS/nixpkgs/tarball/nixos-23.11";
pkgs = import nixpkgs { config = {}; overlays = []; };
in
{
build = pkgs.callPackage ./build.nix {};
}
```
Add an attribute to `default.nix` specifying an environment:
```diff
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`](https://nixos.org/manual/nixpkgs/stable/#sec-pkgs-mkShell-attributes):
```diff
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`:
```nix
# shell.nix
(import ./.).shell
```
Check the development environment, it contains the build-time dependency `cowsay`:
```console
$ nix-shell --pure
[nix-shell]$ cowsay shell.nix
```
## Next steps
- [](pinning-nixpkgs)
- [](./direnv)
- [](python-dev-environment)
- [](packaging-existing-software)