Dynamically loading a javascript file from a non-installed node package

Advertisements

It is currently an idea to build a command line tool which makes my work easier. The command line tool is installed globally with npm install -g name_of_ci.
Another module which is e.g. on my second harddisk D:/ is of course not installed.
Now I want to execute name_of_ci in this folder. Then I read the folder structure and search for special javascript files.
These must then be imported into name_of_ci dynamically.
Of course the dependencies have to be resolved as well.
The folder node_modules is present because for the condition of my tool is that all dependencies are installed.
If I now use import() for this task it is not possible. There I get only an error message that it does not find the module: Cannot find module ‘./dist/test/Test.js’.
But of course the file exists in this path.
What are the possibilities to dynamically load a javascript file with its dependencies?

>Solution :

import() is the correct tool, you’re just not providing the correct path. You have to provide a path that’s relative to the script doing the import(). It sounds like that’s your name_of_ci tool, which is installed globally, so ./dist/test/Test.js will not be a path to the file from that tool’s script. That looks like a path relative to the current directory instead.

You may need to use an absolute path, perhaps retrieved by converting the relative path to an absolute one via path.resolve:

const mod = await import(path.resolve(pathRelativeToCurrentDirectory));
// ...

That will need to be tweaked, of course, but fundamentally it should work.

Leave a ReplyCancel reply