Conditional imports (dynamic imports?)

I’m trying to conditionally import the ckeditor 5 npm package so that my site will still work with IE 11 and having some difficulties.

I have this included in the client:

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))  {
      // If Internet Explorer, return version number
      //alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
      console.log('IE11 does not support ckeditor5');
    }
    else {

      import CKEDITOR from '@ckeditor/ckeditor5-build-classic';

      App.CKEDITOR = CKEDITOR;

      App.getEditor = function(selector) {

<snip>

‘App’ is a global object that I put common functions and objects in.

Is it possible for this to work or do I just have the whole concept of imports/transpiling/babel/es6 wrong?

Is there another way?

thanks,
Cliff

1 Like

You’re almost there. You need to 1) use the correct syntax for the dynamic import and 2) be mindful of its async nature. Perusing the documentation entry for dynamic imports would also be good :wink:

So the above would become:

import('@ckeditor/ckeditor5-build-classic').then(({ default: CKEDITOR }) => {
    App.CKEDITOR = CKEDITOR;
    App.getEditor = function(selector) {};
});

Bonus: in case you want to perform multiple dynamic imports in one go, in the same tick (because they get called and cached at once in the client), you can use promises:

const [
    { default: Obj1 },
    { default: Obj2 },
] = await Promise.all([
    import('some-lib1'),
    import('meteor/my:lazy-loaded-package/client/some-js-file-2'),
]);

Obviously, all of the above works if you have default exports in the imported files. Where you have named exports, get rid of the default: part.

2 Likes

It worked perfectly! Thanks a bunch!

Not really following how this is conditional :thinking: