Artsem Ananich’s Post

JavaScript imports: Old vs Modern — what actually changed? If you started learning JavaScript a few years ago, you probably used require(). Today, most projects use import. At first glance, it looks like just a syntax change. In reality, the difference is much deeper. Here’s what changed. 1. Syntax and structure Old (CommonJS): const fs = require('fs'); module.exports = function greet() {  console.log("Hello"); }; Modern (ES Modules): import fs from 'fs'; export function greet() {  console.log("Hello"); } 2. When modules are loaded - CommonJS loads modules at runtime. - That means require() is executed when the code runs. - ES Modules are statically analyzed before execution. - The structure of imports and exports is known in advance. - This enables better tooling and optimization. 3. Synchronous vs asynchronous behavior CommonJS is synchronous by default. This works well in Node.js but doesn’t fit browsers perfectly. ES Modules are designed with asynchronous loading in mind and work natively in browsers. 4. Dynamic imports With CommonJS, you can require conditionally: if (condition) {  const lib = require('./lib'); } With modern JavaScript, you use dynamic import: if (condition) {  const lib = await import('./lib.js'); } 5. Performance and tree-shaking Because ES Modules are statically analyzable, bundlers can remove unused code (tree-shaking). With CommonJS, this is much harder. Why this matters ES Modules are now the standard for modern JavaScript — in browsers and in Node.js. They improve performance, tooling, and maintainability. CommonJS isn’t “wrong” — it’s just older. But for new projects, ES Modules are the better long-term choice. #JavaScript #ESModules #CommonJS #NodeJS #WebDevelopment #FrontendDevelopment #BackendDevelopment #SoftwareEngineering #Programming #Coding #WebDev #JSDeveloper #Tech #CleanCode

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories