02 / 05

Difference between require and import.

The require()` and import statements serve similar purposes but have some key differences:

require():
  1. 1

    CommonJS Syntax: require('module')

  2. 2

    Synchronous: It loads modules one after another, blocking execution until the module is loaded.

  3. 3

    Supports Both CommonJS and ES Modules: You can use it to import both CommonJS and ES modules.

  4. 4

    No Explicit Default Export Support: It doesn't explicitly support default exports.

  5. 5

    Named Exports via Destructuring: You can use destructuring to import named exports.

  6. 6

    No Static Analysis (Tree Shaking): It doesn't enable tree shaking.

  7. 7

    No Dynamic Importing: It doesn't support dynamic importing.

  8. 8

    Used Primarily in Node.js.

import:
  1. 1

    ES6 Syntax: import module from 'module'

  2. 2

    Asynchronous (Lazy Loading): It loads modules only when needed, improving performance.

  3. 3

    Supports Only ES Modules: Requires .mjs extension for ES modules.

  4. 4

    Explicit Default Export Support: You can directly import default exports.

  5. 5

    Named Exports Directly: You can import named exports directly.

  6. 6

    Static Analysis: Enables tree shaking.

  7. 7

    Dynamic Importing Supported: You can use the import() function.

  8. 8

    Used in Modern JavaScript (Browser and Node.js).