Skip to content
This repository was archived by the owner on Oct 16, 2024. It is now read-only.

Explain how to import local modules recursively #28

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,61 @@ def environment(**options):
return env
```

If you want to import modules from a directory recursively, you can try this approach.

```python
from django.conf import settings
from django.templatetags.static import static
from jinja2 import Environment

from importmap import Importmap


class ImportArguments(TypedDict):
under: str
to: str


def import_recursive(**kwargs: Unpack[ImportArguments]):
root_dir = settings.BASE_DIR
source_dir: str = str(root_dir / kwargs['under'])
source_files = glob(f"{source_dir}/**/*.js", recursive=True)

importmap_dict = {}
for source_file in source_files:
source_module = source_file.split('static/')[-1]
target_module = source_module.replace(source_dir, kwargs['to']).replace(".js", "")

importmap_dict[target_module] = static(source_module)

return importmap_dict


def environment(**options):
env = Environment(**options)
env.globals.update(
{
"importmap": Importmap.json(
development=settings.DEBUG,
extra_imports={
"myjs": static("myjs.js"),
**import_recursive(
under="foo/static/foo",
to="foo"
),
**import_recursive(
under="bar/static/bar",
to="bar"
),

}
)
}
)
return env
```


## Project status

This is partly an experiment,
Expand Down