Exidex7mo ago

Executing module multiple times

I have a script that can be imported using await import() statement. what goes inside brackets is resolved using ModuleLoader. But even if i call await import() multiple times console.logs seem to be executed only on first run. Is there a way to have the module executed multiple times? I want to avoid having to define functions inside a script file
2 Replies
Deno AI Helper
Deno AI Helper7mo ago
I wasn't able to find the answer to your question in the official Deno documentation. However, based on the information you've provided, it's important to note that in JavaScript and TypeScript, which Deno supports, modules are cached after the first time they are imported. This means that subsequent imports of the same module will not re-execute the module code, but rather return the cached module exports. If you want to have module code executed multiple times, you would typically need to export functions from the module and call those functions explicitly each time you want the code to run. Since you mentioned you want to avoid defining functions inside a script file, this might not be the solution you're looking for. One potential workaround, which is not based on the Deno documentation and should be double-checked for accuracy, is to dynamically create a new module identifier for each import. This could involve appending a query string to the module URL, which would make Deno treat it as a new module. However, this is not a standard practice and could lead to other issues such as memory leaks if not managed carefully. Here's a conceptual example of what this might look like:
const uniqueId = Date.now();
const module = await import(`./my-module.js?${uniqueId}`);
const uniqueId = Date.now();
const module = await import(`./my-module.js?${uniqueId}`);
Keep in mind that this advice is speculative and not based on the Deno documentation. You should verify the behavior and ensure it aligns with your project's requirements before implementing such a solution.
raunioroo7mo ago
If you do what the AI suggests, it may work, but keep in mind your module graph will probably keep growing indefinitely as old versions won't be removed (effectively a memory leak) . As that is misusing the import system. You might be better off using eval, or a worker, or another type of alternative architecture.