Lye Fish
Lye Fish

Reputation: 2578

Where does Nim search for modules to import?

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.

Upvotes: 10

Views: 5590

Answers (3)

Tim McNamara
Tim McNamara

Reputation: 18375

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

Upvotes: 1

Reimer Behrends
Reimer Behrends

Reputation: 8740

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"

Upvotes: 15

bluenote10
bluenote10

Reputation: 26709

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.

Upvotes: 3

Related Questions