What is the difference between module.exports and export in Node.js?

← Node.js answers

module.exports with require() is CommonJS, Node's original format. export with import is the standard ES module format. A file is one or the other, decided by its extension or package.json.

// CommonJS (.cjs, or .js without "type": "module")
const add = (a, b) => a + b;
module.exports = { add };
const { add } = require("./math");
 
// ES modules (.mjs, or .js with "type": "module")
export const add = (a, b) => a + b;
import { add } from "./math.js";
  • ES modules need file extensions in relative imports and support top-level await.
  • An ES module can import a CommonJS package, but a CommonJS file cannot use import statements; use dynamic import() instead.
  • Recent Node.js versions can also require() many ES modules, but check your target version.

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required