Importimi dinamik i moduleve ES në JavaScript

Modulet ES mund të importohen në mënyrë dinamike. Kjo aftësi ndonjëherë është e dobishme. Le të shohim se si bëhet kjo. Le të themi se kemi modulin e mëposhtëm:

src/test.jsexport function func1() {
  return '1'
}
export function func2() {
  return '2'
}
export default function() {
  return 'text';
};

Le të themi se duam ta importojmë këtë modul jo menjëherë, por nga ndonjë ngjarje, për shembull, duke klikuar në një buton:

src/index.jsbtn.addEventListener('click', function() {
  
});

Le të importojmë modulin duke përdorur komandën import:

src/index.jsbtn.addEventListener('click', function() {
  import('./test.js');
});

Komanda import si rezultat i saj kthen një premtim:

src/index.jsbtn.addEventListener('click', function() {
  import('./test.js').then(mod => {
    
  });
});

Në ndryshoren e callback do të marrë objektin me funksionet e eksportuara:

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

Ajo që eksportohet si parazgjedhje, do të jetë në çelësin default:

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

Mund të kryhet destrukturosim gjatë importit:

src/index.jsbtn.addEventListener('click', function() {
  import('./test.js').then(({func1, func2}) => {
    let res1 = func1();
    let res2 = func2();
    
    console.log(res1, res2);
  });
});
Задание 1

Krijoni një modul që eksporton një grup emrash të ditëve të javës. Duke klikuar në një buton importoni këtë modul dhe shfaqni ditët e javës në formën e një liste ul.