# Dynamic import of ES modules in JavaScript

ES modules can be imported dynamically. This feature is sometimes useful. Let's see how it's done. Let's say we have the following module:

`export function func1() { return '1' } export function func2() { return '2' } export default function() { return 'text'; };`

Suppose we want to import this module not immediately, but by some event, for example, by clicking on a button:

`btn.addEventListener('click', function() { });`

Let's import a module using the `import` command:

`btn.addEventListener('click', function() { import('./test.js'); });`

The `import` command returns a promise as its result:

`btn.addEventListener('click', function() { import('./test.js').then(mod => { }); });`

The object with exported functions will get into the callback variable:

`btn.addEventListener('click', function() { import('./test.js').then(mod => { let res1 = mod.func1(); let res2 = mod.func2(); console.log(res1, res2); }); });`

What is exported by default will be in the `default` key:

`btn.addEventListener('click', function() { import('./test.js').then(mod => { let dfn = mod.default(); console.log(dfn); }); });`

It can be destructured when importing:

`btn.addEventListener('click', function() { import('./test.js').then(({func1, func2}) => { let res1 = func1(); let res2 = func2(); console.log(res1, res2); }); });`

Create a module that exports an array of the week days names. On a button clicking, import this module and display the days of the week as an `ul` list.

← →
↑
en ru