post's image

[Javascript] Talking about cjs and mjs

Ghost wrote 2 months ago (Feb 26, 2025) with 34 | 2 mins read

What is the core different and when to choose them

CommonJS (CJS) and ES Modules (MJS) is two different way to organize code that help reuse code.

CommonJS (CJS)

  • Use require to load, module.exports to export
  • Use in NodeJS
  • Synchronous Loading suitable with backend side
  • May cause performance issues if load large modules (because it's synchronous)
  • Widely supported in Node.js, but less compatible with browsers (without bundlers).
  • When to choose CJS? => old Node.js projects
  • Build into *.cjs files

ES Modules (MJS)

  • Use import to load, export to export
  • Use in Modern Javascript environment (brower or NodeJS with "type": "module" in package.json)
  • Asynchronous Loading suitable with frontend side
  • Native support in modern browsers and Node.js (from version 12+)
  • Allow static analytic, tree shaking and more efficient bundling.
  • Directly support by modern browser but require transpilation and bundling for legacy browser support.
  • When to choose MJS? => new Node.js projects or frontend projects
  • Build into *.mjs files

What is the order if you have CJS and MJS in the same file?

import { createRequire } from "module"; const require = createRequire(import.meta.url);

require('./file1.js') import './file2.mjs' import './file3.mjs'

function getModule() { import('./file4.mjs') require('./file5.js') }

getModule()

// file1.js
console.log("file1.js") module.exports = {}

// file2.mjs
console.log("file2.mjs") export default {}

// file3.mjs
await new Promise((res) => setTimeout(() => res(), 0)) console.log("file3.mjs") export default {}

// file4.mjs
console.log("file4.mjs") export default {}

// file5.mjs
console.log("file5.js") module.exports = {}

answer is: 2 3 1 5 4