Search code examples
javascriptmoduletypescriptsystemjs

When to include JS libraries using script tags in TypeScript?


I've been having quite a few issues getting TypeScript to work correctly using import statements.

For example, I'm currently working on building an Angular2 application using Leaflet. I've managed to get a few libraries loading correctly, such as Lodash and Leaflet, however now I'm struggling with getting a Leaflet plugin, Leaflet.MarkerCluster to work correctly.

The way I'm importing is as follows:

import L from 'markercluster';

I have the following in my SystemJS definition:

markercluster: 'node_modules/leaflet.markercluster/dist/leaflet.markercluster'

This causes the MarkerCluster file to load and attaches and I can access it from as L.MarkerClusterGroup for example, when I test it in the console.

However, when I run it within a TypeScript module I'm getting an error. I did a bit of digging and this appears to be due to the way that the generated JavaScript is running. The generated JavaScript isn't actually trying to access L (the leaflet global object), but rather, it's accessing:

var m = new markercluster_1.default.MarkerClusterGroup();

Inspecting markercluster_1.default, I can see that it's an empty object. Not sure how to work around this, but I'm thinking if it's even worth using import statements in this situation? Would it make more sense to simply include in a at the top of the page and use ///<reference path='....'> within the TypeScript file where I try to access the module?


Solution

  • Not sure how to work around this, but I'm thinking if it's even worth using import statements in this situation

    My Opinions

    • Steer away from systemjs. Just use webpack.
    • Use require

    Sample:

    import * as leaflet from "leaflet"; 
    // Augment leaflet
    require('./leaflet.markercluster/dist/leaflet.markercluster');
    
    // use new feature
    (leaflet as any).MarkerClusterGroup;
    

    Party 🎉 🌹