Where does Nim search for modules to import?
Asked Answered
A

3

10

When using the import statement, how/where does Nim perform its search for modules?

I know that file paths can be used, but if I don't want to use a file path, where would I put the module I defined locally on my machine?

I haven't used Nimble yet and I assume that's one way, but I'm more interested in how it would be done if the module is only defined locally.

Apicella answered 4/5, 2015 at 18:20 Comment(0)
D
15

Nim searches for modules in the following places:

  1. Relative to the directory of the importing module (via import dir.modname or import dir/modname if it's not in the same directory).
  2. Relative to the directory of the main module (again, via import dir.modname or import dir/modname if it's not in the same directory).
  3. In directories specified by the command line option --path or -p.
  4. In the Nimble package directory, which is usually ~/.nimble/pkgs.
  5. In the standard library.

The command nim dump will show you all the module search paths being used (other than Nimble packages).

You can do the following to use your own modules:

  1. Pass the directory containing them to the compiler using the --path/-p command line option.
  2. Put the same command line option into one of the config files. There are several of them, the global file (for system-wide settings), the user file (for per-user settings), the project file (for project settings), and the parent directory config file(s) (for directories that are parents of the current project directory, for configurations shared by multiple projects). Choose the one with the scope you need.
  3. Use Nimble to install a module for any project done by the current user. For this, create a libname.nimble (replacing libname with the actual name) file in the directory and use nimble install. You can then import the *.nim files in that library directly from any other project. Use nimble uninstall libname to uninstall the library again.

A basic libname.nimble file has the following contents.

[Package]
name = "libname"
author = "Your Name"
version = "0.1"
description = "Example library."
license = "none"
Diwan answered 5/5, 2015 at 10:22 Comment(1)
Lots of great info. Thanks.Apicella
H
3

You basically have two options:

  1. You can pass a search path in the compilation command: nim c -p:~/myModulePath.

  2. You can add search paths to your config/nim.cfg by path="$home/myModulePath". This file also tells you exactly how/where Nim looks for imports by default.

Horizontal answered 5/5, 2015 at 8:39 Comment(1)
Thanks bluenote10. Much appreciated.Apicella
C
1

The nim dump command will show you what's in your path. Take a look at the documentation of the advanced compiler options.

Cerell answered 12/5, 2015 at 4:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.