Creating a Node.js module for both CommonJS & ESM consumption
Matt Braddock
Posted on May 15, 2022
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
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
}
index.js:
const SomeClass = require('./src/index.cjs');
module.exports = SomeClass;
index.mjs:
import SomeClass from './src/index.cjs';
export default SomeClass;
package.json:
"main": "./index.js",
"exports": {
"require": "./index.js",
"import": "./index.mjs"
}
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.
Posted on May 15, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.