import vs require – ESM & commonJs module differences

requireimport
Dynamic evaluationStatic evaluation
Throws error at runtimeThrows error while parsing
Non lexicalLexical



As Node.js uses commonJS moduling, I will refer to the workflow of node to address the commonJS modules. And will refer the ECMAScript modules as ESM.

Syntax difference

CommonJS

dep.js
app.js

ESM

Loading technique difference

The actual loading of any module using require() happens in 5 steps.
  • Resolution
  • Loading
  • Wrapping
  • Evaluation
  • Caching


import()

There is a proposal of import() function too to create nested import statements. Unlike the lexical import keyword, import() function is processed at the time or evaluation (more like require). The syntax is like the following.

use cases

  • On demand module load is possible.
  • Conditional load of modules are also possible
  • Promise like asynchronous handling.

Comments

Popular Posts