Skip to content

subbu963/esm-polyfills

Repository files navigation

Build

esm-polyfills

ES module format is becoming a norm these days with some of the popular modules published as only ES modules(example got, ky). It also comes with a lot of useful features like Top-level await, etc.

But, there are a few features that CommonJS supports but ESM doesnt like these. It becomes a pain to migrate each of these features to a ESM compatible feature and its a lot of manual work. This polyfill tries to support those commonly used and feasible features in ES modules.

Also, i have a detailed it in my blog here.

Available polyfills

  • __filename
  • __dirname
  • require
  • require.resolve

Installation

Using npm:

$ npm install --save @subbu963/esm-polyfills

Using yarn:

$ yarn add @subbu963/esm-polyfills

Usage

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

Then in your <your-script>.mjs file, globals like __filename, __dirname, require and require.resolve will be automatically available:

console.log('__filename', __filename);
console.log('__dirname', __dirname);
console.log(require('lodash'), require.resolve('lodash'), require('../package.json'));

If you dont want to auto polyfill, then you can programmatically import them and use it in your code like this:

$ ESM_POLYFILLS_GLOBAL=false node <your-script>.mjs

Then in your <your-script>.mjs file, do:

import { getFileName, getDirName, getRequire as _require_ } from '@subbu963/esm-polyfills';

const __filename = getFileName();
const __dirname = getDirName();

console.log('__filename', __filename);
console.log('__dirname', __dirname);
console.log(_require_('lodash'), _require_.resolve('lodash'));

Comparision with other libraries

There are other libraries which serve the same purpose like:

But these packages arent actually polyfills. They require you to manually import those libraries and use __dirname, __filename, etc from them. My polyfill aims to get away with this manual process and use those commonjs functionality directly in a ES module like you are in a commonjs module.