DEV Community

Cover image for Using CommonJS Modules in NodeJS with module.exports and require() | Cheatsheet
Saurabh Misra
Saurabh Misra

Posted on • Originally published at saurabhmisra.dev

Using CommonJS Modules in NodeJS with module.exports and require() | Cheatsheet

This blog post serves as a quick reference aka cheatsheet( primarily intended for my future self ), to understand the syntactic peculiarities of the CommonJS style of module exports in NodeJS with a quick glance.

While NodeJS now supports ES6 modules, there are still a lot of projects out there that use CommonJS modules which is why NodeJS hasn't dropped support for them and doesn't seem like it will, in the near future.

Default Export

You can directly assign a value to module.exports.

const display = () => console.log( "Hello World" );

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

And then while using require(), you can either use the same name or a different one.

const display = require( "./my-module" );
display();

// or

const show = require( "./my-module" );
show();
Enter fullscreen mode Exit fullscreen mode

Named Exports

Named Exports can be done in one of the following ways:

const display = () => console.log( "Hello World" );

exports.display = display;

// or

module.exports.display = display;

// or

module.exports = {
  display
};
Enter fullscreen mode Exit fullscreen mode

While requiring or importing these named exports, we can choose one of the following options.

// import everything into one object
const myModule = require( "./my-module" );
myModule.display();

// or

// import only selected properties from module.exports
const { display } = require( "./my-module" );
display();

// or

// another way to reference only a single property while require()-ing  
const display = require( "./my-module" ).display;
display();
Enter fullscreen mode Exit fullscreen mode

Hope this helps!🙏

Top comments (0)