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 andrequire()
in the AMD technology (requireJS library)?
- 3 Possible duplicate of Using Node.js require vs. ES6 import/export – Sarah Groß Commented Apr 7, 2019 at 15:52
-
4
@connum disagree, there is a difference between
import()
andimport
. – Jonas Wilms Commented Apr 7, 2019 at 16:26 - 1 Dynamic import is still a proposal, it's not part of ES6. – Bergi Commented Apr 7, 2019 at 18:47
- 1 It is introduced on 21 November 2017 on the official V8 website. Also, can be found on MDN website officially. Yes, it is a standard. v8.dev/features/dynamic-import – oyilmaztekin Commented Jan 31, 2020 at 8:01
2 Answers
Reset to default 3There 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 es 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.
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)