Search code examples
reactjsnode.jsnpm

_dirname is not defined in ES module scope


I encountered a problem where I received a reference error stating "_dirname is not defined in ES module scope". This occurred after I made a change in the package.json file by setting the type to "module". Could someone please offer a solution?

import { fileURLToPath } from "url";
console.log(__dirname); // Reference Error: 
// __dirname is not defined in ES module scope

Solution

  • refer to this documentation, and do it this way

    import path from 'path';
    import { fileURLToPath } from 'url';
    const __filename = fileURLToPath(import.meta.url);
    
    const __dirname = path.dirname(__filename);
    
    console.log(__dirname);
    

    import.meta.url as described here

    This is defined exactly as in browsers which provide the URL of the current form file.

    then adding to your package.json

     "type": "module",