DEV Community

Matt Braddock
Matt Braddock

Posted on

5 4

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.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay