HomeAbout MeContact

How to fix "ReferenceError: __dirname/__filename/require is not defined in ES module scope"

By Aditya Subramanyam
Published in Javascript
February 22, 2023
1 min read
How to fix "ReferenceError: __dirname/__filename/require is not defined in ES module scope"

How to fix “ReferenceError: dirname/filename/require is not defined in ES module scope”

When you are migrating from commonjs module type to es modules, you will often face ReferenceError: __dirname/__filename/require is not defined in ES module scope. You get this error cause __dirname, __filename and require doesnt exist in ES modules. They exist only in CommonJs modules. However, there are ways to polyfill these.

The easiest way is to use a polyfill like esm-polyfills which will auto fix the above issue.

$ npm install --save @subbu963/esm-polyfills
$ node -r @subbu963/esm-polyfills <your-script>.mjs

Doing -r @subbu963/esm-polyfills will auto import @subbu963/esm-polyfills before running your script. This will automatically polyfill, __dirname, __filename and require in that script.

If you for any reason want to manually do it, you can do:

import { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';

function getFileName(url) {
  return fileURLToPath(url)
}
function getDirName(url) {
  return dirname(getFileName(url));
}
function getRequire(url) {
  return createRequire(url);
}
const __filename = getFileName(import.meta.url);
const __dirname = getDirName(import.meta.url);
const require = getRequire(import.meta.url);

console.log('Using commonjs require to import path module', require('path'));

Tags

javascript
Previous Article
Using import maps
Aditya Subramanyam

Aditya Subramanyam

Architect

Topics

Javascript

Related Posts

Loading CSS inside ES Modules
June 19, 2023
1 min

Quick Links

Advertise with usAbout UsContact Us

Social Media