What is the correct way of importing members of a workspace?
As title suggests, I am wondering what the correct way of setting up a deno workspace with multiple modules where Module-A imports functions from Module-B? Are there restrictions in circular imports? I was reading over the standard library, but it did not make immediate sense as to how to set this up.
3 Replies
In a Deno workspace, you can set up multiple modules and import functions from one module into another using "bare specifiers" that are defined in the
deno.json
configuration files of each module. Here's how you can do it according to the documentation:
1. Define a workspace: In your root deno.json
, you define a workspace by specifying its members, which are directories expected to have their own deno.json(c)
and/or package.json
files.
2. Name your workspace members: In each member directory, you should have a deno.json
file where you define a "name"
field. This name is used to reference the workspace member throughout your workspace.
For example, in the add
module, you would have:
And in the subtract
module:
3. Import using bare specifiers: In your code, you can then import functions from these modules using the names defined in their respective deno.json
files.
For instance, in your main.ts
:
Regarding circular imports, the documentation does not explicitly mention restrictions on circular imports within a workspace. However, it's generally a good practice to avoid circular dependencies as they can lead to complex dependency graphs and potential runtime issues. The Deno style guide, while not directly addressing workspaces, advises minimizing dependencies and avoiding circular imports to keep internal dependencies simple and manageable.
If you need to have modules that depend on each other, you shouldcarefully design your modules to ensure that the dependencies are one-way wherever possible, or that the circular dependencies do not cause issues during runtime. 🦕
Unfortunately this did not answer my question