What is difference between:
dynamic
import()
in the ES6+ technology andrequire()
in the AMD technology (requireJS library)?
What is difference between:
dynamic import()
in the ES6+ technology and
require()
in the AMD technology (requireJS library)?
There are a few differences:
require()
is synchronous, import()
is asynchronous (returns a Promise).
import
is a keyword defined in the ECMA spec, require()
is just a function defined by some library.
You can use require()
"natively" in NodeJS and not in browsers, and import()
is specified for all JavaScript engines.
Now if you use a building pipeline (e.g. Webpack), they do actually do different things:
require()
will bundle the required code into one bundle, just as import stuff
would, whereas import()
dynamically loads the module at runtime, just as require.ensure
would (doc)
There are some differences but import()
can be considered as an official implementation of the legacy AMD libraries like require.js
. Also, it brings a modern approach.
The self-evident feature of a legacy AMD is that it comes with the module definition besides import expression. This means you can define a module that can be imported asynchronously anywhere in the project.
If you don't have a transpiler like BABEL
to polyfill EcmaScript proposals on your project or if you work on the legacy codebase and need an AMD solution for improving performance, considering to use some AMD libraries instead of dynamic import can be a better choice.