Import module from nested directories in Elm?
Asked Answered
C

1

5

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?

Clam answered 20/2, 2018 at 14:45 Comment(0)
B
6

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
Bradski answered 20/2, 2018 at 14:48 Comment(2)
This solved it! I wasn't aware that you have to mirror the directory structure when exposing modules. Thanks for your fast reply!Clam
Yep, the module name must match the path of the file. That's how the Elm compiler looks up a module's file for each import.Bradski

© 2022 - 2024 — McMap. All rights reserved.