Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix module env usage tip #1423

Merged
merged 2 commits into from
Jun 6, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 17 additions & 11 deletions book/modules.md
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ As you can see, defining the submodule structure also shapes the command line AP

## Environment Variables

Modules can also define an environment using [`export-env`](/commands/docs/export-env.md):
Modules can define an environment using [`export-env`](/commands/docs/export-env.md):

```nu
# greetings.nu
Expand All @@ -292,22 +292,28 @@ hello Arthur, King of the Britons!
```

::: tip
You can put a complex code defining your environment without polluting the namespace of the module, for example:
The module implementation can use its own scoped environment variables without them bleeding into users scope. For example:

```nu
def tmp [] { "tmp" }
def other [] { "other" }
# greetings-local.nu

let len = (tmp | str length)

load-env {
OTHER_ENV: (other)
TMP_LEN: $len
}
export def hello [] {
$env.MYNAMELOCAL = "Arthur, King of the Britons"
$"hello ($env.MYNAMELOCAL)"
}
```

Only `$env.TMP_LEN` and `$env.OTHER_ENV` are preserved after evaluating the `export-env` module.
```nu
> use greetings-local.nu

> $env.MYNAMELOCAL
Error: nu::shell::column_not_found
[…]

> greetings-local hello
hello Arthur, King of the Britons!
```

:::

## Caveats
Expand Down