import vs require – ESM & commonJs module differences
require | import |
---|---|
Dynamic evaluation | Static evaluation |
Throws error at runtime | Throws error while parsing |
Non lexical | Lexical |
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()
require()
happens in 5 steps.
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.
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.
Comments
Post a Comment