Reputation: 8609
I have this directory tree:
project
|
-> dir1
|
-> dir2
|
-> module.mjs
server.mjs
utils.mjs
My current working directory is:
project/
Source code of server.mjs
async function main(){
var module = await import("./dir1/dir2/module.mjs");
}
main();
Source code of module.mjs
//this works!
import utils from "../../utils.mjs";
//this fails!
import utils from "./utils.mjs";
It seems that the static import in the module.mjs consider the dot '.' as the directory of itself, not the current working directory.
How to set a current directory for dynamic import?
And the actual base question is: How to avoid the long '../../.......' of static imports in a dynamic module.
For example, I wish to have something like this in server.mjs:
var module = await import("./dir1/dir2/module.mjs",{cwd:"project/"});
Or, in dynamic module, able to use:
import utils from './utils.mjs'
instead of:
import utils from '../../long dot dot/utils.mjs'
Upvotes: 3
Views: 3160
Reputation: 8609
It seems like there's no way to do static import in a dynamic imported module with the dot .
refer to current working directory yet.
So, the work-around is still using the dotdot-slashslash...
I've submitted a new feature request to Node.js team here: https://github.com/nodejs/node/issues/31822
Upvotes: 0
Reputation: 1332
Try process.cwd()
, it returns the directory from which you run nodejs.
Upvotes: 3