How to conditionally import library in angular depending on browser platform

Viewed 1630

I need to import a library dynamically depending on the browser platform. To prevent Angular Universal from giving errors because its using the window object.

import * as Muuri from 'muuri';

So what I want is something like this:

if (isPlatformBrowser(this.platform)) {
     import * as Muuri from 'muuri';
    }
    else {
  declare var Muuri;
}

Obviously this doesn't work.

3 Answers

No, unfortunately you can't conditionally import libraries. What you can do though is import both libraries, inject both in your constructor and then conditionally using isDevMode(), (there exists no isDebugMode()) you can use whatever you prefer for each case.

This is not a very good solution though, as it means you will load both libs in memory and since you inject them in the constructor the treeshaking that happens at build time will not ommit them.

If this is done sparingly it might even not make a difference though (negatively). I suggest you benchmark Memory size at runtime using dev tools and if there is significant gain to outweigh the manual nature of the cleaner approach, then just replace the Mock class in the import when you are done developing the feature using that Mock

Try this

exportToExcel() {
    import("xlsx").then(xlsx => {
      // JUST USE THE LIBRARY
    });
  }

try this code.

    if (!isPlatformServer(this.platformId)) {
      const Muuri = (await import('muuri')).default;
      // or const Muuri = (await import('muuri'));
    }
Related