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

Fri, 04 Nov 2022 17:45:15 GMT

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')