Sobes.tech
Junior

What are ES modules?

sobes.tech AI

Answer from AI

ES modules are the standard way to organize code in JavaScript, based on the import and export syntax.

Main features:

  • Standard: Part of the ECMAScript specification, supported by most modern browsers and runtime environments like Node.js.
  • Explicit dependency management: Modules explicitly specify what values they export and what values they import from other modules.
  • Static structure: Module dependencies are determined at compile time (or parsing), not at runtime. This allows static analysis tools like bundlers (Webpack, Rollup) to optimize code.
  • Isolation: Each variable, function, or class declared inside a module is, by default, local to that module. To make them accessible outside, they need to be explicitly exported.
  • Asynchronous support: Modules can be loaded asynchronously in browsers, without blocking page load.

Syntax:

  • Export:
    // app.js
    export const myVariable = 123; // Named export
    export function myFunction() { // Named export
      console.log('Hello from module!');
    }
    export default class MyClass { // Default export
      constructor() {
        console.log('MyClass instance created');
      }
    }
    
  • Import:
    // main.js
    import { myVariable, myFunction } from './app.js'; // Named import
    import MyDefaultClass from './app.js'; // Default import
    
    console.log(myVariable); // 123
    myFunction(); // Hello from module!
    const instance = new MyDefaultClass(); // MyClass instance created
    

Comparison with CommonJS (Node.js):

Feature ES Modules CommonJS
Syntax import, export require, module.exports, exports
Dependencies Static (determined before execution) Dynamic (determined at runtime)
Loading Asynchronous (in browsers) Synchronous
this in root undefined module.exports
Support Browsers, Node.js (by default from version 13.2, via --experimental-modules flag before that) Mainly Node.js

Using ES modules is the recommended approach for modern frontend development due to their standardization, better tool support, and static analysis capabilities.