Halvard
Halvard•2mo ago

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
Deno AI Helper
Deno AI Helper•2mo ago
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.
{
"workspace": ["./add", "./subtract"]
}
{
"workspace": ["./add", "./subtract"]
}
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:
{
"name": "@scope/add",
"version": "0.1.0",
"exports": "./mod.ts"
}
{
"name": "@scope/add",
"version": "0.1.0",
"exports": "./mod.ts"
}
And in the subtract module:
{
"name": "@scope/subtract",
"version": "0.3.0",
"exports": "./mod.ts"
}
{
"name": "@scope/subtract",
"version": "0.3.0",
"exports": "./mod.ts"
}
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:
import { add } from "@scope/add";
import { subtract } from "@scope/subtract";
import { add } from "@scope/add";
import { subtract } from "@scope/subtract";
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 should
Deno AI Helper
Deno AI Helper•2mo ago
carefully design your modules to ensure that the dependencies are one-way wherever possible, or that the circular dependencies do not cause issues during runtime. 🦕
Halvard
Halvard•2mo ago
Unfortunately this did not answer my question