logo

How to fix "__dirname is not defined in ES module scope" in JS

Posted on
Authors

Problem

Lines of code looks like this

import path from 'path'

path.join(__dirname, 'children')
import path from 'path'

path.join(__dirname, 'children')

will produce the error

ReferenceError: __dirname is not defined in ES module scope
ReferenceError: __dirname is not defined in ES module scope

Solution

Update your code looks like this

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

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

path.join(__dirname, 'children')

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

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

path.join(__dirname, 'children')