DEV Community

Matt Braddock
Matt Braddock

Posted on

Creating a Node.js module for both CommonJS & ESM consumption

Last week I had an urge to create a simple stopwatch module for a future project. I recently got my feet wet with creating ECMAScript modules (ESM), and wanted to ensure that any module I created in the future would feel native to either CommonJS or ESM. Turns out it is very simple.

In the most skeleton form, my structure looked like this:

src/
└── index.cjs
index.js
index.mjs
package.json
Enter fullscreen mode Exit fullscreen mode

All of the work for the module lives in src/, with the two root index files just providing exports to be consumed by parent modules. Here is how the relevant portions of the files above look:

src/index.cjs:

module.exports = class SomeClass {
    // code here
}
Enter fullscreen mode Exit fullscreen mode

index.js:

const SomeClass = require('./src/index.cjs');

module.exports = SomeClass;
Enter fullscreen mode Exit fullscreen mode

index.mjs:

import SomeClass from './src/index.cjs';

export default SomeClass;
Enter fullscreen mode Exit fullscreen mode

package.json:

"main": "./index.js",
"exports": {
    "require": "./index.js",
    "import": "./index.mjs"
}
Enter fullscreen mode Exit fullscreen mode

And that's it! This can certainly be scaled up to more than a single export, and it can include named exports as well.

Bonus: here is the stopwatch module I created.

Top comments (0)