Home Explore Blog CI



nushell

6th chunk of `book/modules/creating_modules.md`
91e77eefda9b0c700a13fd8ae4dab5ce0cf3f7b1ddd537350000000100000818
   2. The second `use my-utils []` imports nothing _but_ the environment into `go.nu`'s exported environment block. Because the `export-env` of `go.nu` is executed when the module is first imported, the `use my-utils []` is also evaluated.

Note that the first method keeps `my-utils` environment inside the `go.nu` module's scope. The second, on the other hand, re-exports `my-utils` environment into the user scope.

### Module files and commands cannot be named after parent module

A `.nu` file cannot have the same name as its module directory (e.g., `spam/spam.nu`) as this would create an ambiguous condition with the name being defined twice. This is similar to the situation described above where a command cannot have the same name as its parent.

## Windows Path Syntax

::: important
Nushell on Windows supports both forward-slashes and back-slashes as the path separator. However, to ensure that they work on all platforms, using only the forward-slash `/` in your modules is highly recommended.
:::

## Additional Examples

### Local Definitions

As mentioned above, definitions in a module without the [`export`](/commands/docs/export.md) keyword are only accessible in the module's scope.

To demonstrate, create a new module `is-alphanumeric.nu`. Inside this module, we'll create a `str is-alphanumeric` command. If any of the characters in the string are not alpha-numeric, it returns `false`:

```nu
# is-alphanumeric.nu
def alpha-num-range [] {
    [
        ...(seq char 'a' 'z')
        ...(seq char 'A' 'Z')
        ...(seq 0 9 | each { into string })
    ]
}

export def "str is-alphanumeric" []: string -> bool {
    if ($in == '') {
        false
    } else {
        let chars = (split chars)
        $chars | all {|char| $char in (alpha-num-range)}
    }
}
```

Notice that we have two definitions in this module -- `alpha-num-range` and `str is-alphanumeric`, but only the second is exported.

```nu
use is-alphanumeric.nu *
'Word' | str is-alphanumeric
# => true
'Some punctuation?!' | str is-alphanumeric
# => false
'a' in (alpha-num-range)

Title: Module Scope, Naming Conventions, and Local Definitions in Nushell
Summary
The chunk details how modules handle environment imports and scope. It explains that the second `use my-utils []` imports only the environment into a module's exported environment block. It also covers that a `.nu` file cannot share a name with its module directory to avoid ambiguity. It recommends using forward-slashes for Windows paths for cross-platform compatibility. Finally, it demonstrates local definitions within modules, using an example of an `is-alphanumeric` module with an internal `alpha-num-range` function that is not exported.