How to `callPackage` within a custom nixpkgs import?

This page recommends creating a Node.js builder with buildNodeJs = pkgs.callPackage <nixpkgs/pkgs/development/web/nodejs/nodejs.nix> {};. That works when running in an existing Nix environment, but when using nix-shell --pure it says I need to specify the nixpkgs using -I or NIX_PATH. The problem is that that would duplicate the pkgs I’ve already defined within the same scope. How do I instead pkgs.callPackage the same file within the pkgs which is already in scope? I’ve tried a few variants like buildNodeJs = pkgs.callPackage pkgs.nodejs {};, but that fails with

opening file ‘/nix/store/…-nodejs-…/default.nix’: No such file or directory

This is presumably because default.nix isn’t part of the derivation output, but is there some other way to build Node.js using the pkgs within the current context as the reference?

Please give this a try:

buildNodeJs = pkgs.callPackage "${toString pkgs.path}/pkgs/development/web/nodejs/nodejs.nix" {};
2 Likes

Also prefer ${toString pkgs.path} instead of ${pkgs.path} to prevent the directory being moved to another Nix store path.

Oh, indeed pkgs.path is not a string but a path. Thanks for pointing this out. I’ll add this to my previous post so that lazy search engine users don’t have to read the thread :slight_smile:

Do you have a reference for this? I’m not sure what it’s referring to.

See, for example, A digression into coercions section of this blog post (rest is unrelated).