Short comparison of the most common statements in CommonJS vs. ESM/ECMAScript for importing, exporting and in your package.json.
See the table below for a brief comparison on the most used statements that should cover the vast majority of use-cases.
Use-Case | CommonJS | ESM / ECMAScript |
---|---|---|
Importing | ||
Default import (NPM module) | const imp = require('module'); | import imp from 'module'; |
Default import (own module) | const imp = require('./myModule'); Note: path is mandatory, file extension is optional | import imp from './myModule.js'; Note: path and file extension are mandatory |
Named import | const { namedImp } = require('module'); | import { namedImp } from 'module'; |
Import with function invocation | const funcImp = require('module')(myParam); | import imp from 'module'; Note: ESM doesn’t support invocations on importing, so two lines of code are needed |
Exporting | ||
Default export (unnamed) | module.exports = function() {/* */} | export default function() {/* */} |
Named export (e.g. a function, works also with objects, classes etc.) | module.exports.myFunction = function() {/* */} | export function myFunction() {/* */} |
Exporting an arrow function | module.exports.myFunction = () => {/* */} | export const MyFunction = () => {/* */} Note: the const keyword is needed here |
package.json entries | ||
Module type | …nothing… or "type": "commonjs" Note: since CommonJS is the default, normally no type entry is present in package.json | "type": "module" Note: this tells Node.js to treat all .js files as ES modules without the need to use the .mjs extension which is often preferred |
Entry point | "main": "index.js" | "exports": "./index.js" Note: path and file extension are mandatory |
Please note that this cheat-sheet is just an excerpt of all possible module.exports
/require
and import
/export
constellations as well as all available package.json
options. For more details, refer to the very comprehensive documentation sites:
If you are about to migrate from CommonJS, also check out the article on converting an existing Node.js project to ESM.
Happy coding 😉