5

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.

Raymond the Developer
  • 1,576
  • 5
  • 26
  • 57
  • Check out this https://netbasal.com/using-typescript-dynamic-imports-in-angular-d210547484dd – Arun Kumar Mar 04 '20 at 11:46
  • Does this answer your question? [angular universal: dynamic imports for browser only](https://stackoverflow.com/questions/40751383/angular-universal-dynamic-imports-for-browser-only) – kvetis Mar 04 '20 at 11:48
  • @ArunKumar I am not sure how to implement it: if (isPlatformBrowser(this.platform)) { const moduleSpecifier = '* as Muuri from "muuri"'; import(moduleSpecifier).then(module => { Muuri = module; }); }? – Raymond the Developer Mar 04 '20 at 11:56

3 Answers3

0

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

Sanjay Lohar
  • 520
  • 2
  • 8
  • But if I do this it still will result in "ReferenceError: window is not defined" this error right? Is there really no way to make this work? – Raymond the Developer Mar 04 '20 at 12:00
  • Universal toolkit renders code on the Server Side and window object is only available in browsers that is why you are getting this error. You can add condition to execute client side code only on browser by using isPlatformBrowser module . – Sanjay Lohar Mar 04 '20 at 12:04
  • I know that. But I need to conditionally import a library. Thats the question I asked. – Raymond the Developer Mar 04 '20 at 12:05
0

Try this

exportToExcel() {
    import("xlsx").then(xlsx => {
      // JUST USE THE LIBRARY
    });
  }
Sanjay Lohar
  • 520
  • 2
  • 8
0

try this code.

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