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

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

    import path from 'path';
    const __dirname = path.join(path.dirname(decodeURI(new URL(import.meta.url).pathname))).replace(/^\\([A-Z]:\\)/, "$1");
    

    This code also works on Windows. (the replacement is safe on other platforms, since path.join returns back-slash separators only on Windows)

提交回复
热议问题