logologo

Isomorphic `__dirname`

Aug 30, 2021 · 1min

In ESM, you might found your old friends __dirname and __filename are no longer available. When you search for solutions, you will find that you will need to parse import.meta.url to get the equivalents. While most of the solutions only show you the way to get them in ESM only, If you like me, who write modules in TypeScript and transpile to both CJS and ESM at the same time using tools like tsup. Here is the isomorphic solution:

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

const _dirname = typeof __dirname !== 'undefined'
  ? __dirname
  : dirname(fileURLToPath(import.meta.url))
import { dirname } from 'path'
import { fileURLToPath } from 'url'

const _dirname = typeof __dirname !== 'undefined'
  ? __dirname
  : dirname(fileURLToPath(import.meta.url))
CC BY-NC-SA 4.0 2021-PRESENT © Anthony Fu