
Dynamic Import in JavaScript
At the beginning of last year, it was proposed to introduce dynamic import into JavaScript. If anyone does not know, now only static import is natively supported in JavaScript, and there are reasons for this, but this is a topic for another discussion. The proposal was implemented and included in the list of upcoming ECMAScript updates. Google Chrome with version 63 already supports this feature. I'll tell you a little what it is and where it can come in handy.
Dynamic import is used in much the same way as static import, but it has several key differences:
Syntactically dynamic import is similar to function call: import ('path / to / module.js');
The import ('path / to / file.js') command returns Promise, which will go into the fulfilled state after the module itself is pulled up and installed directly, as well as all its dependencies. And this means that we can write like this:
import('path/to/module.js')
.then(module => {
module.loadPageInto(main);
})
.catch(err => {
main.textContent = err.message;
});
Or even like this:
const module = await import('path/to/module.js');
Important note: although dynamic import is syntactic and looks like a call to the import () function, it is not a function. It is not inherited from Function.prototype, which means that it cannot be called via call or apply.
There are many applications for dynamic import, require.js has long had a similar opportunity and webpack, if I'm not mistaken, too, so many of you have probably used this functionality for a long time. Now it will be possible to do this natively. But on the other hand, the ability to import dynamically, depending on conditions, during runtime also provides a place for more confusing code, although I understand that you can stick a bad code with anything, it’s not the tool. Write your opinion in the comment, what do you think of dynamic import.
You can read and see in more detail here:
https://github.com/tc39/proposal-dynamic-import
https://developers.google.com/web/updates/2017/11/dynamic-import
https: // www. youtube.com/watch?v=eg8eLH52d4s&t=31s