Search code examples
pythonimportelmmulti-module

Import module from nested directories in Elm?


If I have a directory structure like this:

src
 ├── Commands.elm
 ├── Decoders.elm
 ├── Main.elm
 ├── Messages.elm
 ├── Models.elm
 ├── Page
 │   ├── Cats
 │   │   ├── Main.elm
 │   │   ├── Style.elm
 │   │   └── ...
 │   ├── Pieces
 │   │   ├── Main.elm
 │   │   ├── Style.elm
 │   │   └── ...
 │   └── Players
 │       ├── Main.elm
 │       ├── Style.elm
 │       └── ...
 ├── Routing.elm
 ├── Style
 │   ├── Index.elm
 │   ├── MainCss.elm
 │   └── Main.elm
 ├── Update.elm
 └── View.elm

I found some examples that show how to import a module from a directory, but I couldn't find an example on how to import a module from a sub-driectory. For example, how do I import Page/Cats/Main.elm in View.elm?

In Python I would put a __init__.py into each nested directory to turn them into packages which would allow me to reach the modules in them like this from Page import Cats or like this from Page.Cats import Main. Is there a similar concept in Elm?


Solution

  • Assuming src is in source-directories in elm-package.json, just make sure the module name in that file matches the path, i.e. Page.Cats.Main:

    module Page.Cats.Main exposing (add)
    
    add x y = x + y
    

    and then import that in View.elm:

    import Page.Cats.Main
    
    -- You can now call functions defined in that module like this:
    -- Page.Cats.Main.add 1 2