📜 ⬆️ ⬇️

Dynamic JavaScript Import

At the beginning of last year, it was proposed to introduce the possibility of dynamic import into JavaScript. If anyone does not know, now in JavaScript only static import is natively supported and there are reasons for this, but this is a topic for another conversation. The offer has been implemented and is included in the list of the nearest ECMAScript update. Google Chrome 63 version already supports this feature. I'll tell you a little about what it is and where it can be useful.


Dynamic import (dynamic import) is used almost as well as static, but has several key differences:


Syntactically, a dynamic import is similar to a function call: import ('path / to / module.js');


The import command ('path / to / file.js') returns a Promise, which will go to the fulfilled state after the module itself is pulled and installed directly, as well as all its dependencies. This means that we can write 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 syntactically and looks like a call to the import () function, but it is not a function. It is not inherited from Function.prototype, which means that it cannot be called via call or apply.


You can find many uses for dynamic imports, require.js has a similar possibility for a long time and webpack, if I am not mistaken too, therefore many of you, probably, have been using similar functionality for a long time. Now you can do it natively. But on the other hand, the ability to import dynamically, depending on the conditions, during runtime gives also a place for more confusing code, although I understand that you can stick bad code with anything, not in a tool case. Write your opinion in the comments what you think about dynamic import.


In more detail you can read and see 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


')

Source: https://habr.com/ru/post/455200/


All Articles