CJS <vs> MJS

CommonJS: CommonJS modules have been around since Node.js was born in 2009. They do things in sync, step by step. When you import or export, it's all figured out as the script runs.

CommonJS relies on filename, dirname, and NODE_PATH variables, which help locate things. ESM doesn't really bother with those.

ESM: ESM, or ECMAScript modules, strutted onto the JavaScript stage in 2015 with ES6. These modules are more about that asynchronous life. They sort out their imports and exports way before the script runs. It's like planning things out before starting the race.

ESM shows off with top-level await, which lets you wait for stuff right in the file, no async functions required. CommonJS just doesn't do that.

Package.json: For CommonJS, you'd spot "type": "commonjs" in the package.json. On the other hand, ESM proudly claims its identity with "type": "module". But honestly, I've never seen anyone claim to be CommonJS in their package.json. ESM seems to be the cool kid on the block.

Imports and Exports: CommonJS brings in files with var module = require('file path'); whereas ESM takes a more modern approach with import defaultStuff, { namedStuff } from 'file path';.

When it comes to exports, CommonJS uses module.exports and exports for default and named stuff, while ESM prefers export default name and export name.

File Extensions: Node.js assumes .js and .ts files are CommonJS, playing nice by default. But CommonJS likes .cjs for JavaScript and .cts for TypeScript. ESM shows its colors with .mjs for JavaScript and .mts for TypeScript.

Runtime Environments: CommonJS feels at home in all versions of Node.js, but ESM is out there making friends in browsers and Node.js versions 12 and up.

Strict Mode and 'this': CommonJS asks for 'use strict' at the file's start, while ESM is inherently strict. In CommonJS, 'this' points at exports, but in ESM, 'this' is like that mysterious friend who doesn't show up - it's undefined.

Both have their perks, but ESM is like that newer, flashy option, while CommonJS is the sturdy foundation that's been around for ages.

要查看或添加评论,请登录

Umang Sharma的更多文章

社区洞察

其他会员也浏览了