1

I have a Mapbox web map in my Angular 2 application.

The map attaches itself to a <div> tag, like so:

<div id="map"></div>

I have two different libraries I can use for my web map: Mapbox GL JS, which uses WebGL, or Mapbox.js, which does not use WebGL and is more compatible with older computers and browsers.

When the user loads my application, I want to test to see if their browser can use the WebGL library. (Example here from Mapbox documentation.)

If they support it, I want to load the Mapbox GL JS library.

If they do not support it, I want to load Mapbox.js instead as a fallback.

(Vanilla Javascript example of this behavior here.)

I want to do this without loading both libraries. I only want to load one library or the other, and all of the associated code that I have written. (Each library has its own different syntax/formatting, so I cannot reuse the same associated code for either library.)

What do you think is the best strategy for doing this in an Angular 2 application using the Webpack module bundler?

NOTE: In this instance, I cannot use the router to separate the two different maps; otherwise this could be a lot easier....

3
  • 1
    Without routing, can't you just use System.import?
    – Jack Guy
    Jan 25, 2017 at 22:27
  • 1
    @ Harangue - I think your'e right. also, this post already answered this question... at least in my opinion
    – ymz
    Jan 25, 2017 at 22:35
  • Brilliant! Thank you both very much.
    – MattSidor
    Jan 25, 2017 at 23:02

1 Answer 1

0

A good solution (for Webpack) is to use either System.import or require.ensure, as explained in this answer: https://stackoverflow.com/a/34489991/3403895

System.import method:

export class MyAppComponent {
  constructor(){
    System.import('path/to/your/module').then(refToLoadedModule => {
      refToLoadedModule.someFunction();
    }
  );
}

require.ensure method:

export class MyAppComponent {
  constructor() {
     require.ensure(['path/to/your/module'], require => {
        let yourModule = require('path/to/your/module');
        yourModule.someFunction();
     }); 
  }
}

This link also seems to be a good tutorial for this: Code Splitting in Angular 2 with Webpack 2 (http://blog.waffle.io/code-splitting-angular-2-webpack-2/)

Many thanks to Harangue and ymz

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.