Solve - __dirname is not defined in ES module scope in JS


Borislav Hadzhiev

Tue Oct 19 20211 min read


Photo by Roi Dimor

Solve - __dirname is not defined in ES module scope #

The "__dirname is not defined in ES module scope" error occurs when we try to try to use the __dirnameglobal variable in an ES module file. The__dirnameor __filename global variables are not available in ECMAScript module files.

dirname is not defined in es module scope

To solve the "__dirname is not defined in ES module scope" error, import and use the dirname() method from the path module. The dirname method takes a path as a parameter and returns the directory name of the path.

import path from 'path'; import {fileURLToPath} from 'url'; const __filename = fileURLToPath(import.meta.url); // ๐Ÿ‘‡๏ธ "/home/john/Desktop/javascript" const __dirname = path.dirname(__filename); console.log('directory-name ๐Ÿ‘‰๏ธ', __dirname); // ๐Ÿ‘‡๏ธ "/home/borislav/Desktop/javascript/dist/index.html" console.log(path.join(__dirname, '/dist', 'index.html'));

To get the filename, we had to use the fileURLToPath method from the url module.

The fileURLToPath method returns the fully-resolved platform-specific Node.js file path.

The only parameter the method takes is the file URL string, which should be converted to a path.

The import.meta object contains context-specific metadata for the module - e.g. the module's URL.

// ๐Ÿ‘‡๏ธ file:///home/john/Desktop/javascript/index.js console.log(import.meta.url);

To get the directory name, we used the dirname method from the path module.

Here's the output from logging the __filename and __dirname variables from the above snippet on my machine.

get dirname response

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee