How do I store part of my packages in a separate file?

Hi,
I’ve recently started using NixOS and would like to store part of my defined packages, in a separate file (packages.nix). I would like to import the file into my configuration.nix and then do something along the lines of:

environment.systemPackages = with pkgs; [
package1
package2
] ++ myPackages;

with myPackages being a variable of the content imported from packages.nix. This however, just doesn’t seem to work the way I want it to.

packages.nix would look something like this:

{ pkgs }: with pkgs; [ p1 p2 p3 ]

which I would then import using

myPackages = import ./packages.nix { inherit pkgs; };

Unfortunatly neither this, nor other things I tried seemed to work. I also tried this whole mkOptions thing, but it still won’t work and even if it did, I can’t imagine that being the best approach available to me.

You can do that in theory, but it’s nicer to just use the module system as intended. If you write to a list in two different modules, the NixOS module system will merge them:

# configuration.nix
{ pkgs, ... }: {
  imports = [
    ./myPackages.nix
  ];

  environment.systemPackages = with pkgs; [
    package1
    package2
  ];
}
# myPackages.nix
{ pkgs, ... }: {
  environment.systemPackages = with pkgs; [
    p1
    p2
    p3
  ];
}

Custom options are usually a code smell IMO, they’re practically never necessary if you use the module system well, unless you want to write a new module for something completely independent from scratch. Composition should be done with the module system, not import/conditions.

1 Like

This worked, thank you very much! I thought redefining environment.systemPackages would overwrite the other one, which doesn’t seem to be the case.

Yep, the NixOS module system merges together all values defined in different modules (~files). If the module system can’t merge something nix will give you an error telling you to use mkForce or such, this is true for simple strings or such (though there’s also types.lines which look like strings and get merged together just fine).

2 Likes