Import Mapping Libraries from a URL

When adding functionality to a web page using JavaScript, you may rely on external libraries (like a mapping library) to provide that functionality so you do not need to write it yourself. There are many ways to use, or import, these libraries into the page. A new method is to use ES Modules to import third-party JavaScript libraries into your application from a URL. Using this method is easier because downloading or installing via NPM is not necessary.

For mapping applications with the ArcGIS API for JavaScript, I’ve found that using this “ES Modules via CDN URL” pattern is great for quick samples or debugging. This pattern should not be used for production code - see notes in the documentation here.

To use this pattern, the key is to add type="module" to your <script> tag. For the ArcGIS API for JavaScript, the URL pattern is to take whatever import string is shown in the API documentation (for example, @arcgis/core/views/MapView), and:

  1. prepend https://js.arcgis.com/X.XX/ (where X.XX is the version number, like 4.22), and
  2. append .js to the end.

So if you want a plain HTML and JavaScript file solution, it would look like this:

<script type="module">
    import MapView from 'https://js.arcgis.com/4.22/@arcgis/core/views/MapView.js';

When using code-sharing websites like CodePen, you do not have control over the <script> tag, so you might think using this pattern will not work. Luckily, these websites have embraced ES Modules and have a solution.

CodePen

CodePen will automatically add the type="module" tag to your <script> tag if it detects that you’re using ES Modules. Details on that here.

CodePen - ArcGIS JS API - ES Modules Template

CodeSandbox

In CodeSandbox, if you use the “esm-react” environment you can use ES Modules.

CodeSandbox - ArcGIS JS API - ES Modules Template

Leaflet and Esri Leaflet

For libraries like Leaflet or Esri Leaflet where ES Module builds are not provided (yet), you can use the Skypack CDN like this:

import * as L from "https://cdn.skypack.dev/[email protected].1";
import * as esriLeaflet from "https://cdn.skypack.dev/[email protected]";
import * as esriLeafletVector from "https://cdn.skypack.dev/[email protected]";

CodePen - Esri Leaflet - ES Modules Template

I periodically write about technology, maps, open data, and other software topics. To get updates about new posts:

See Also