mirror of
https://codeberg.org/mhwombat/nix-book.git
synced 2025-12-29 17:54:57 +08:00
78 lines
1.1 KiB
Text
78 lines
1.1 KiB
Text
= Import
|
|
|
|
The built-in `import` function provides a way to parse a `.nix` file.
|
|
|
|
[source,nix]
|
|
.a.nix
|
|
....
|
|
{
|
|
message = "You successfully imported me!";
|
|
b = 12;
|
|
}
|
|
....
|
|
|
|
[source]
|
|
.Example
|
|
....
|
|
nix-repl> a = import ./a.nix
|
|
|
|
nix-repl> a.message
|
|
"You successfully imported me!"
|
|
|
|
nix-repl> a.b
|
|
12
|
|
....
|
|
|
|
[NOTE]
|
|
====
|
|
If path supplied to the `import` function is a directory,
|
|
the file default.nix in that directory is imported.
|
|
====
|
|
|
|
The scope of the imported file does not inherit the scope of the importer.
|
|
|
|
[source,nix]
|
|
.b.nix
|
|
....
|
|
x + 7
|
|
....
|
|
|
|
[source]
|
|
.Example
|
|
....
|
|
nix-repl> x = 12
|
|
|
|
nix-repl> y = import ./b.nix
|
|
|
|
nix-repl> y
|
|
error:
|
|
… while calling the 'import' builtin
|
|
at «string»:1:2:
|
|
1| import ./b.nix
|
|
| ^
|
|
|
|
error: undefined variable 'x'
|
|
at /home/amy/codeberg/nix-book/b.nix:1:1:
|
|
1| x + 7
|
|
| ^
|
|
2|
|
|
....
|
|
|
|
So to pass information when importing something, use a function.
|
|
|
|
[source,nix]
|
|
.c.nix
|
|
....
|
|
x: x + 7
|
|
....
|
|
|
|
[source]
|
|
.Example
|
|
....
|
|
nix-repl> f = import ./c.nix
|
|
|
|
nix-repl> f 12
|
|
19
|
|
....
|
|
|
|
The imported file may import other files, which may in turn import more files.
|