5

What is difference between:

  • dynamic import() in the ES6+ technology and

  • require() in the AMD technology (requireJS library)?

Adrian Trabka
  • 151
  • 3
  • 9
  • 3
    Possible duplicate of [Using Node.js require vs. ES6 import/export](https://stackoverflow.com/questions/31354559/using-node-js-require-vs-es6-import-export) – Constantin Groß Apr 07 '19 at 15:52
  • 3
    @connum disagree, there is a difference between `import()` and `import`. – Jonas Wilms Apr 07 '19 at 16:26
  • 1
    Dynamic import is still a proposal, it's not part of ES6. – Bergi Apr 07 '19 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. https://v8.dev/features/dynamic-import – oyilmaztekin Jan 31 '20 at 08:01

2 Answers2

2

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)

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
2

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.

oyilmaztekin
  • 713
  • 1
  • 7
  • 25