简体   繁体   中英

How to set current directory for ES6 dynamic import function

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'

尝试process.cwd() ,它返回运行 nodejs 的目录。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM