I would like to know the difference between require(x)
and await import(x)
in terms of code splitting and lazy loading. Are they both the same? If yes, then why does await import(x)
exist in the first place as one can use require()
statements anywhere he wants. Any in depth answer would be highly appreciated.
Difference between require() and await import()
Asked Answered
They are not the same. I think you should read this:
https://medium.com/computed-comparisons/commonjs-vs-amd-vs-requirejs-vs-es6-modules-2e814b114a0b
import is when requiring an es module, that's the new ecma script standard, it has many benefits over require (common js modules)
import(x)
allows you to selectively load only the items you need, so it can help save memoryimport(x)
can be run asynchronously, so better performance
© 2022 - 2024 — McMap. All rights reserved.
require
is still used when you don't use Babel transpiller. Reason is thatimport
,export
keywords were added to JS in ES6 andasync/await
was added in ES8. This is why you seerequire
d modules in Node.js butimports
in React for ex. – Scalesrequire
is CommonJS specific syntax that is supported by Node, but not by browsers. I predates ES modules. ES modules are standardized now and supported in more and more environments. – Lavone