CommonJS vs ESM Differences in Node.js
📖 Scenario: You are building a simple Node.js project that uses modules to organize code. You want to understand the difference between CommonJS and ESM (ECMAScript Modules) by creating examples of each and seeing how to export and import functions.
🎯 Goal: Build two small modules: one using CommonJS syntax and one using ESM syntax. Then import and use these modules in separate main files to see how the syntax differs.
📋 What You'll Learn
Create a CommonJS module file named
mathCommonJS.js that exports a function add which adds two numbers.Create an ESM module file named
mathESM.mjs that exports a function multiply which multiplies two numbers.Create a CommonJS main file named
index-cjs.js that imports and uses the add function from the CommonJS module and an ESM main file named index-esm.mjs that imports and uses the multiply function from the ESM module.Use
require() to import the CommonJS module and import statement to import the ESM module.Ensure the project runs correctly with Node.js 20+.
💡 Why This Matters
🌍 Real World
Node.js projects often use modules to organize code. Understanding CommonJS and ESM helps you work with different libraries and write modular code.
💼 Career
Many Node.js jobs require knowledge of module systems to maintain and build scalable applications. Knowing how to switch between CommonJS and ESM is valuable.
Progress0 / 4 steps