How to fix “__dirname is not defined in ES module scope”
I was recently playing around with creating a PoC to extract tokens from Figma which produces a JSON object and then parse this JSON to generate other formats such as CSS, SCSS, JS etc …
While building my script, I came across the below error
ReferenceError: __dirname is not defined
I set the module to ESNext
in the tsconfig.json which triggered a different problem of not understanding .ts file. I updated the tsconfig,json to add a new section for ts-node related config and setesm: true
The solution to fix the above ReferenceError: __dirname is not defined
was to use it in the below way
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
The above code is what bundlers generate, when they encounter the usage of the __dirname term in our code. Since, I have my custom configuration and do not use bundlers, I did it the manual way. Doing things manually teaches us more about the internals of how things work — a good way to feed our inner curiosity bug!