Basic Flake structure#
A typical flake.nix is an attribute set in which outputs is a function that takes inputs and returns an output attribute set.
{
description = "我的 NixOS 配置";
inputs = {
# 这里定义依赖
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
home-manager.url = "github:nix-community/home-manager";
};
outputs = { self, nixpkgs, ... }@inputs: {
# 这里定义产出(系统配置、软件包、Shell 环境等)
nixosConfigurations.my-host = nixpkgs.lib.nixosSystem {
system = "x86_64-linux";
modules = [ ./configuration.nix ];
};
};
}1. Inputs#
inputs contains the external resources you want to reference.
nixpkgs: the entire package repository.
home-manager: a user-level configuration tool.
flake-utils: a commonly used helper library.
The
followskeyword: very important! It makes a specified nested input follow the top-level nixpkgs, reducing duplicate nixpkgs sources in the dependency graph. Multiple package versions may still exist, and sharing an input does not guarantee compatibility across all external projects.home-manager.inputs.nixpkgs.follows = "nixpkgs";
2. Outputs#
outputs contains what your Flake produces.
nixosConfigurations: used bynixos-rebuild; your system is at its core.homeConfigurations: used byhome-manager.devShells: development environments used bynix develop.packages: software you package yourself.
What are self and @inputs here?#
self: represents the current Flake itself. You can use it to reference files defined within it.@inputs: syntactic sugar that captures all input arguments together.
Practical tip: understand the outputs hierarchy#
Running nix flake show displays the outputs as a tree. Those levels must match exactly in your code for nixos-rebuild to find your configuration.
References & further reading
Adapted from technical notes. Examples use generic names.
Continue along a reading path
Flakes: project and dependency management
- 01Flake structure: inputs and outputs
- 02flake.lock and reproducibility
- 03Flake Utils and project templates
- 04External Flake references and collaboration
- 05Migrating NixOS configuration to Flakes
- 06A tutorial on Flake projects and dependency management
- 07How Flake updates work
- 08Rolling back and manually editing flake.lock