Home > Enterprise >  Dynamic import with multiple modules
Dynamic import with multiple modules

Time:07-25

I had this code before and it worked fine (just showing the imports here):

import { Calendar } from '@fullcalendar/core';
import dayGridPlugin from '@fullcalendar/daygrid';

I thought I can load them dynamically, but I don't think I'm doing right. I changed to this:

let calendarEl = document.getElementById('fullcalendar');

if(calendarEl) {
    Promise.all([
        import(/* webpackChunkName: 'fullcalendar-core' */ '@fullcalendar/core'),
        import(/* webpackChunkName: 'fullcalendar-daygrid' */ '@fullcalendar/daygrid')
    ])
    .then(([{Calendar}, dayGridPlugin]) => {
        let calendar = new Calendar(document.getElementById('fullcalendar'), {
            plugins: [dayGridPlugin]
        });
    
        calendar.render();    
    })
    .catch(console.warn);

My calendar doesn't load, the error message is: Cannot read properties of undefined (reading 'length') and it points to the let calendar = new Calendar row.

enter image description here

CodePudding user response:

This one worked for me at the end:

let calendarEl = document.getElementById('fullcalendar');

if(calendarEl) {
    (async () => {
        const {Calendar} = await import('@fullcalendar/core');
        const {default: dayGridPlugin} = await import('@fullcalendar/daygrid');

        let calendar = new Calendar(calendarEl, {
            plugins: [dayGridPlugin],
            initialView: 'dayGridMonth'
        });
        
        calendar.render();
    })();
}

CodePudding user response:

The import dayGridPlugin from … declaration is a default import. So you'll need to use

.then(([{Calendar}, {default: dayGridPlugin}]) => {
    const calendar = new Calendar(document.getElementById('fullcalendar'), {
        plugins: [dayGridPlugin]
    });
    calendar.render();    
})
  • Related