How to export binary packages of all build inputs?

After running nix-build I can list the result and all its runtime dependencies using nix-store -qR result. Then I can feed that list into nix-store --export in order to share my locally built package.

Is there some way to do the same for build dependencies? (For instance, to share locally built dependencies.)

I can list all the build dependencies’ derivations using nix-store -qR $(nix-store -qd result), but AFAIU passing that list to nix-store --export will only put in the derivations, not the built packages.

Is there some way to do what I want?

Some of the comments and suggestion from How to get the build-time dependencies of a package? · Issue #1245 · NixOS/nix · GitHub may be what you are looking for. Either the in-Nix and CLI approaches?

One option is to get the recursive build time deps by building the ‘.inputDerivation’ of a derivation. That includes a lot more than the direct build deps, but I think it’s still worth mentioning.

Based on the links above I put together the following, which seems to work well enough.

nix-store --export $(nix-store --query --references $(nix-instantiate -A pkg) \
      | xargs nix-store --realise \
      | xargs nix-store --query --requisites) >

I’m not sure it’s minimal, but at least it contains everything needed to build.