JavaScript require vs import
I was asked this question in one of my front-end interviews and answered it incorrectly, which inspired me to write this blog post.
We use either require or import to use code/data defined in other files(such as helpers.js, data.json ) in the current file.
Differences
import
is part of ES6 spec whereasrequire
is old school
- With
require
, you can’t select what you need even if you don't need some part of it. butimport
allows you to selectively choose.
- Loading is synchronous (step by step) for
require
on the other handimport
can be asynchronous(without waiting for previous import) so it can perform a little better thanrequire
.
- You can call require anywhere in your file but import needs to be called at top.
- In react, you can use the required to dynamically import other components which in turn reduces the chunk size on the first load.