When it comes to async or maybe lazy loading, then import ()
is much more powerful. See when we require the component in asynchronous way, then we use import
it in some async manner as in const
variable using await
.
const module = await import('./module.js');
Or if you want to use require()
then,
const converter = require('./converter');
Thing is import()
is actually async in nature. As mentioned by neehar venugopal in ReactConf, you can use it to dynamically load react components for client side architecture.
Also it is way better when it comes to Routing. That is the one special thing that makes network log to download a necessary part when user connects to specific website to its specific component. e.g. login page before dashboard wouldn't download all components of dashboard. Because what is needed current i.e. login component, that only will be downloaded.
Same goes for export
: ES6 export
are exactly same as for CommonJS module.exports
.
NOTE - If you are developing a node.js project, then you have to strictly use require()
as node will throw exception error as invalid token 'import'
if you will use import
. So node does not support import statements.
UPDATE - As suggested by Dan Dascalescu: Since v8.5.0 (released Sep 2017), node --experimental-modules index.mjs
lets you use import
without Babel. You can (and should) also publish your npm packages as native ESModule, with backwards compatibility for the old require
way.
See this for more clearance where to use async imports - https://www.youtube.com/watch?v=bb6RCrDaxhw