Skip to content

Instantly share code, notes, and snippets.

@SanariSan
Last active February 27, 2022 17:21
Show Gist options
  • Save SanariSan/8fce307f7d1ad1fd76a3f995c976e219 to your computer and use it in GitHub Desktop.
Save SanariSan/8fce307f7d1ad1fd76a3f995c976e219 to your computer and use it in GitHub Desktop.
__dirname / __filename with "Modules"

Replacement for __dirname and __filename when using Modules over CommonJS

import {fileURLToPath} from 'url';
import path from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(fileURLToPath(import.meta.url));

However, in most cases, this is better:

import {fileURLToPath} from 'url';

const foo = fileURLToPath(new URL('foo.js', import.meta.url));

And many Node.js APIs accept URL directly, so you can just do this:

const foo = new URL('foo.js', import.meta.url);

Cut from: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v38.0.0/docs/rules/prefer-module.md

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment