Alternative for __dirname in node when using the --experimental-modules flag

前端 未结 9 1848
旧时难觅i
旧时难觅i 2020-12-01 06:03

I use the flag --experimental-modules when running my node application in order to use ES6 modules.

However when I use this flag the metavariable

相关标签:
9条回答
  • 2020-12-01 06:50

    As Geoff pointed out the following code returns not the module's path but working directory.

    import path from 'path';
    const __dirname = path.resolve();
    

    works with --experimental-modules

    0 讨论(0)
  • 2020-12-01 06:51

    There have been proposals about exposing these variables through import.meta, but for now, you need a hacky workaround that I found here:

    // expose.js
    module.exports = {__dirname};
    
    // use.mjs
    import expose from './expose.js';
    const {__dirname} = expose;
    
    0 讨论(0)
  • 2020-12-01 06:52
    process.cwd()
    

    From documentation:

    The process.cwd() method returns the current working directory of the Node.js process.

    0 讨论(0)
提交回复
热议问题