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

前端 未结 9 1904
旧时难觅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:39

    For Node 10.12 +...

    Assuming you are working from a module, this solution should work, and also gives you __filename support as well

    import path from 'path';
    import { fileURLToPath } from 'url';
    
    const __filename = fileURLToPath(import.meta.url);
    const __dirname = path.dirname(__filename);
    

    The nice thing is that you are also only two lines of code away from supporting require() for CommonJS modules. For that you would add:

    import { createRequireFromPath } from 'module';
    const require = createRequireFromPath(__filename); 
    

提交回复
热议问题