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.
importis part of ES6 spec whereas
requireis old school
require, you can’t select what you need even if you don't need some part of it. but
importallows you to selectively choose.
- Loading is synchronous (step by step) for
requireon the other hand
importcan be asynchronous(without waiting for previous import) so it can perform a little better than
- 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.