import
builtins.import
Nix manual
Takes 1 arguments
path
Load, parse, and return the Nix expression in the file path.
Note
Unlike some languages,
importis a regular function in Nix.
The path argument must meet the same criteria as an interpolated expression.
If path is a directory, the file default.nix in that directory is used if it exists.
Example
$ echo 123 > default.nixImport
default.nixfrom the current directory.import ./.123
Evaluation aborts if the file doesn’t exist or contains an invalid Nix expression.
A Nix expression loaded by import must not contain any free variables, that is, identifiers that are not defined in the Nix expression itself and are not built-in.
Therefore, it cannot refer to variables that are in scope at the call site.
Example
If you have a calling expression
rec { x = 123; y = import ./foo.nix; }then the following
foo.nixthrows an error:# foo.nix x + 456since
xis not in scope infoo.nix. If you wantxto be available infoo.nix, pass it as a function argument:rec { x = 123; y = import ./foo.nix x; }and
# foo.nix x: x + 456The function argument doesn’t have to be called
xinfoo.nix; any name would work.
Noogle detected
import :: Path -> a
Implementation
This function is implemented in c++ and is part of the native nix runtime.
static RegisterPrimOp primop_import(
{.name = "import",
.args = {"path"},
// TODO turn "normal path values" into link below
.doc = R"(
Load, parse, and return the Nix expression in the file *path*.
> **Note**
>
> Unlike some languages, `import` is a regular function in Nix.
The *path* argument must meet the same criteria as an [interpolated expression](@docroot@/language/string-interpolation.md#interpolated-expression).
If *path* is a directory, the file `default.nix` in that directory is used if it exists.
> **Example**
>
> ```console
> $ echo 123 > default.nix
> ```
>
> Import `default.nix` from the current directory.
>
> ```nix
> import ./.
> ```
>
> 123
Evaluation aborts if the file doesn’t exist or contains an invalid Nix expression.
A Nix expression loaded by `import` must not contain any *free variables*, that is, identifiers that are not defined in the Nix expression itself and are not built-in.
Therefore, it cannot refer to variables that are in scope at the call site.
> **Example**
>
> If you have a calling expression
>
> ```nix
> rec {
> x = 123;
> y = import ./foo.nix;
> }
> ```
>
> then the following `foo.nix` throws an error:
>
> ```nix
> # foo.nix
> x + 456
> ```
>
> since `x` is not in scope in `foo.nix`.
> If you want `x` to be available in `foo.nix`, pass it as a function argument:
>
> ```nix
> rec {
> x = 123;
> y = import ./foo.nix x;
> }
> ```
>
> and
>
> ```nix
> # foo.nix
> x: x + 456
> ```
>
> The function argument doesn’t have to be called `x` in `foo.nix`; any name would work.
)",
.impl = [](EvalState & state, const PosIdx pos, Value ** args, Value & v) {
import(state, pos, *args[0], nullptr, v);
}})