Node.js module formats with ESM and CommonJS

Choose the right module format for Node.js files and troubleshoot mismatches between import syntax and runtime configuration.

🎯 Introduction

By the end of this article, you will be able to choose the right module format for Node.js files and troubleshoot mismatches between import syntax and runtime configuration.


🛠 Run ESM in Node.js

The import and export syntax follows the ES6 modules course. When running directly in Node.js, also check whether a file loads as ES Modules (ESM) or CommonJS (CJS). A format mismatch can prevent otherwise valid module code from running.

The NPM course covers dependency installation, project scripts, and lockfiles. Here we only use the package.json settings that determine the Node.js module format.

First create greet.mjs. The .mjs extension explicitly tells Node.js to use ESM:

greet.mjs
export const greet = name => `Hello, ${name}`

Create an entry file in the same directory:

main.mjs
import { greet } from './greet.mjs'
console.log(greet('Alex'))

Run node main.mjs to print Hello, Alex. Here, ./greet.mjs is relative to the entry file. Include the extension even if your frontend build tool allows omitting it.

Existing Node.js projects also frequently use CommonJS, which organizes modules with require and module.exports. The following implements the same task with this syntax.


⚖️ CommonJS: export a value, then retrieve it

Export with module.exports

Save greet.cjs. The .cjs extension explicitly indicates CJS:

greet.cjs
module.exports = name => `Hello, ${name}`

module.exports is the value this file provides to other modules: a function in this case. To expose several features, you can export an object instead.

Import with require

Save main.cjs in the same directory and run node main.cjs:

main.cjs
const greet = require('./greet.cjs')
console.log(greet('Alex'))

The result is still Hello, Alex. require() returns the target file's module.exports, so greet is a callable function.

Existing code may also add export properties with exports.greet = .... Initially, exports refers to the same export object. Assigning exports = ... only reassigns that local variable; it does not replace the actual export. Use module.exports = ... to replace the entire exported value.


🧰 Set type explicitly when using .js

.mjs and .cjs specify the format directly. If your team uses .js, declare type in package.json, the project configuration file:

package.json
{
    "type": "module"
}

module makes .js files in the package scope use ESM; commonjs makes them use CJS. The nearest enclosing package.json generally determines the configuration.

To verify this, rename the ESM files to greet.js and main.js, and change the import path to ./greet.js. Keep the configuration above in the same directory, then run node main.js. It still prints the greeting.

Runnable examples throughout this course use ESM and .mjs. This article includes CommonJS comparisons and a .js type configuration example to explain the differences.

❓ Questions and answers

Q1: Why does omitting an extension work in Vue projects but fail here?

Frontend build tools may resolve incomplete paths for you. Local imports in directly executed Node.js ESM must specify the full file path.

Q2: Is renaming .cjs to .mjs enough?

No. You must also replace require, module.exports, and related code with the corresponding ESM syntax.

Q3: Can I use require directly in ESM?

It is unavailable by default. Each set of examples uses one consistent format. Follow a third-party package's import instructions when using it.


🧪 Exercise

Change both ESM example files to .js, configure package.json, and update the import path. Verify that node main.js still prints the greeting. Then change the configuration to "type": "commonjs" and observe the error caused by the format mismatch.

// Write your code here

🎉 Try these techniques with your own examples!