A tiny library to help load ArcGIS API for JavaScript modules in non-Dojo applications
Clone or download
tomwayson Merge pull request #139 from JamesMilnerUK/patch-2
Add Dojo 2+ example to README examples
Latest commit 60aa31c Oct 15, 2018

README.md

esri-loader

Travis npm npm npm GitHub stars

A tiny library to help load modules from either the 4.x or 3.x versions of the ArcGIS API for JavaScript in non-Dojo applications.

ArcGIS logo, mended broken heart, Angular logo, Ember logo, Rreact logo, Vue logo

See below for more information on why this library is needed and how it can help improve application load performance and allow using the ArcGIS API in isomorphic/universal applications.

NOTE: If you want to use the ArcGIS API in an Ember or AngularJS (1.x) application, you should use one of these libraries instead:

Otherwise you'll want to follow the Install and Usage instructions below to use this library directly in your application.

See the Examples section below for links to applications that use this library.

Table of Contents

Install

npm install --save esri-loader

or

yarn add esri-loader

Usage

The code snippets below show how to load the ArcGIS API and its modules and then use them to create a map. Where you would place similar code in your application will depend on which application framework you are using. See below for example applications.

Loading Styles

Before you can use the ArcGIS API in your app, you'll need to load the styles that correspond to the version you are using. You can use the provided loadCss(url) function. For example:

// load esri styles for version 4.9 using loadCss
esriLoader.loadCss('https://js.arcgis.com/4.9/esri/css/main.css');

Alternatively, you can manually load them by more traditional means such as adding <link> tags to your HTML, or @import statements to your CSS. For example:

<!-- load esri styles for version 4.9 via a link tag -->
<link rel="stylesheet" href="https://js.arcgis.com/4.9/esri/css/main.css">
@import url('https://js.arcgis.com/4.9/esri/css/main.css');

or:

/* load esri styles for version 3.26 via import */
@import url('https://js.arcgis.com/3.26/esri/css/esri.css');

Loading Modules from the ArcGIS API for JavaScript

Here's an example of how you could load and use the 4.x Map and MapView classes in a component to create a map (based on this sample):

// first, we use Dojo's loader to require the map class
esriLoader.loadModules(['esri/views/MapView', 'esri/WebMap'])
.then(([MapView, WebMap]) => {
  // then we load a web map from an id
  var webmap = new WebMap({
    portalItem: { // autocasts as new PortalItem()
      id: 'f2e9b762544945f390ca4ac3671cfa72'
    }
  });
  // and we show that map in a container w/ id #viewDiv
  var view = new MapView({
    map: webmap,
    container: 'viewDiv'
  });
})
.catch(err => {
  // handle any errors
  console.error(err);
});

Lazy Loading the ArcGIS API for JavaScript

In the above snippet, the first time loadModules() is called, it will attempt to lazy load the most recent 4.x version of the ArcGIS API if it has not already been loaded by calling loadScript() for you. Subsequent calls to loadModules() will not attempt to load the script once loadScript() has been called.

If you don't want to use the latest version of the ArcGIS API hosted on Esri's CDN, you'll need to pass options with the URL to whichever version you want to use. For example, the snippet below uses v3.x of the ArcGIS API to create a map.

// if the API hasn't already been loaded (i.e. the frist time this is run)
// loadModules() will call loadScript() and pass these options, which, 
// in this case are only needed b/c we're using v3.x instead of the latest 4.x
const options = {
  url: 'https://js.arcgis.com/3.26/'
};
esriLoader.loadModules(['esri/map'], options)
.then(([Map]) => {
  // create map with the given options at a DOM node w/ id 'mapNode'
  let map = new Map('mapNode', {
    center: [-118, 34.5],
    zoom: 8,
    basemap: 'dark-gray'
  });
})
.catch(err => {
  // handle any script or module loading errors
  console.error(err);
});

Lazy loading the API is a useful pattern if your users may never end up visiting any routes that need the API (i.e. show a map or 3D scene).

See the Advanced Usage section below for more advanced techniques such as pre-loading the ArcGIS API, using in isomorphic/universal applications, configuring Dojo, and more.

Why is this needed?

Unfortunately, you can't simply npm install the ArcGIS API and then import ArcGIS modules directly from other modules in a non-Dojo application. The only reliable way to load ArcGIS API for JavaScript modules is using Dojo's AMD loader. However, when using the ArcGIS API in an application built with another framework, you typically want to use the tooling and conventions of that framework rather than the Dojo build system. This library lets you do that by providing an ES module that you can import and use to dynamically inject an ArcGIS API script tag in the page and then use its Dojo loader to load only the ArcGIS API modules as needed.

There are a few different solutions to this problem, but this blog post explains why you should be using esri-loader if your ArcGIS web application uses any other module loader besides the Dojo loader (i.e. webpack, rollup.js, etc.). Using esri-loader enables you to:

This is because esri-loader let's you control when the ArcGIS API and its modules are loaded and used. You can lazy load the API and modules only on routes that require them to render a map, or you can pre-load the API without blocking rendering. You can ensure the API and its modules are not loaded/used when rendering on the server where they will cause errors.

Examples

Here are some applications and framework-specific wrapper libraries that use this library. We don't gurantee that these examples are current, so check the version of esri-loader their commit history before using them as a reference. They are presented by framework in alphabetical order - not picking any favories here 😜:

Angular

Reusable libraries for Angular

Example Angular applications

CanJS

  • can-arcgis - CanJS configureable mapping app (inspired by cmv-app) and components built for the ArcGIS JS API 4.x, bundled with StealJS

Choo

  • esri-choo-example - An example Choo application that shows how to use esri-loader to create a custom map view.

Dojo 2+

  • esri-dojo - An example of how to use Esri Loader with Dojo 2+. This example is a simple map that allows you to place markers on it.

Electron

  • ng-cli-electron-esri - This project is meant to demonstrate how to run a mapping application using the ArcGIS API for JavaScript inside of Electron

Ember

See the examples over at ember-esri-loader

Glimmer.js

Hyperapp

  • esri-hyperapp-example - An example Hyperapp application that shows how to use esri-loader to create a custom map view and component.

Ionic

  • ionic2-esri-map - Prototype app demonstrating how to use Ionic 3+ with the ArcGIS API for JavaScript

Preact

  • esri-preact-pwa - An example progressive web app (PWA) using the ArcGIS API for JavaScript built with Preact

React

Reusable libraries for React

Example React applications

Riot

  • esri-riot-example - An example Riot application that shows how to use esri-loader to create a custom <esri-map-view> component.

Stencil

  • esri-stencil-example - An example Stencil application that shows how to use esri-loader to create a custom map view component and implement some basic routing controlling the map state

Vue.js

Advanced Usage

Pre-loading the ArcGIS API for JavaScript

If you have good reason to believe that the user is going to transition to a map route, you may want to start pre-loading the ArcGIS API as soon as possible w/o blocking rendering, for example:

// preload the ArcGIS API
// NOTE: in this case, we're not passing any options to loadScript()
// so it will default to loading the latest 4.x version of the API from the CDN
this.loadScriptPromise = esriLoader.loadScript();

// later, for example once a component has been rendered,
// you can wait for the above promise to resolve (if it hasn't already)
this.loadScriptPromise
.then(() => {
  // you can now load the map modules and create the map
})
.catch(err => {
  // handle any script loading errors
  console.error(err);
});

Isomorphic/universal applications

This library also allows you to use the ArcGIS API in isomorphic or universal applications that are rendered on the server. There's really no difference in how you invoke the functions exposed by this libary, however you should avoid trying to call them from any code that runs on the server. The easiest way to do this is to use them in component lifecyle hooks that are only invoked in a browser, for example, React's componentDidMount or Vue's mounted. See tomwayson/esri-loader-react-starter-kit for an example of a component that lazy loads the ArcGIS API and renders a map only once a specific route is loaded in a browser.

Alternatively, you could use checks like the following to ensure these functions aren't invoked on the server:

if (typeof window !== 'undefined') {
  // this is running in a browser, 
  // pre-load the ArcGIS API for later use in components
  this.loadScriptPromise = esriLoader.loadScript();
}

Configuring Dojo

You can pass a dojoConfig option to loadScript() or loadModules() to configure Dojo before the script tag is loaded. This is useful if you want to use esri-loader to load Dojo packages that are not included in the ArcGIS API for JavaScript such as FlareClusterLayer.

// in this case options are only needed so we can configure dojo before loading the API
const options = {
  // tell Dojo where to load other packages
  dojoConfig: {
    async: true,
    packages: [
      {
        location: '/path/to/fcl',
        name: 'fcl'
      }
    ]
  }
};
esriLoader.loadModules(['esri/map', 'fcl/FlareClusterLayer_v3'], options)
.then(([Map, FlareClusterLayer]) => {
  // you can now create a new FlareClusterLayer and add it to a new Map
})
.catch(err => {
  // handle any errors
  console.error(err);
});

Using your own script tag

It is possible to use this library only to load modules (i.e. not to pre-load or lazy load the ArcGIS API). In this case you will need to add a data-esri-loader attribute to the script tag you use to load the ArcGIS API for JavaScript. Example:

<!-- index.html -->
<script src="https://js.arcgis.com/3.26/" data-esri-loader="loaded"></script>

ArcGIS Types

This library doesn't make any assumptions about which version of the ArcGIS API you are using, so you will have to manually install the appropriate types.

4.x Types

Follow these instructions to install the 4.x types.

NOTE: For Angular CLI applications, you will also need to add "arcgis-js-api" to compilerOptions.types in src/tsconfig.app.json and src/tsconfig.spec.json as shown here.

Then you can use the __esri namespace for the types as seen in this example.

3.x Types

Unfortunately the __esri namespace is not defined for 3.x types. You can use these instructions to install the 3.x types, but then you will still need to use import statements to get the types. This may cause build errors that may or may not result in actual runtime errors depending on your environment.

Updating from previous versions

From < v1.5

If you have an application using a version that is less than v1.5, this commit shows the kinds of changes you'll need to make. In most cases, you should be able to replace a series of calls to isLoaded(), bootstrap(), and dojoRequire() with a single call to loadModules().

From angular-esri-loader

The angular-esri-loader wrapper library is no longer needed and has been deprecated in favor of using esri-loader directly. See this issue for suggestions on how to replace angular-esri-loader with the latest version of esri-loader.

Dependencies

Browsers

This library doesn't have any external dependencies, but the functions it exposes to load the ArcGIS API and its modules expect to be run in a browser. This library officially supports the same browers that are supported by the latest version of the ArcGIS API for JavaScript. Since this library also works with v3.x of the ArcGIS API, the community has made some effort to get it to work with some of the older browsers supported by 3.x like IE < 11.

You cannot run the ArcGIS API for JavaScript in Node.js, but you can use this library in isomorphic/universal applications as well as Electron. If you need to exectue requests to ArcGIS REST services from something like a Node.js CLI application, see arcgis-rest-js.

Promises

Since v1.5 asynchronous functions like loadScript() and loadModules() return Promises, so if your application has to support browers that don't support Promise (i.e. IE) you have a few options.

If there's already a Promise implementation loaded on the page you can configure esri-loader to use that implementation. For example, in ember-esri-loader, we configure esri-loader to use the RSVP Promise implementation included with Ember.js.

  init () {
    this._super(...arguments);
    // have esriLoader use Ember's RSVP promise
    esriLoader.utils.Promise = Ember.RSVP.Promise;
  },

Otherwise, you should consider using a Promise polyfill, ideally only when needed.

Issues

Find a bug or want to request a new feature? Please let us know by submitting an issue.

Contributing

Esri welcomes contributions from anyone and everyone. Please see our guidelines for contributing.

Licensing

Copyright 2017 Esri

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

A copy of the license is available in the repository's LICENSE file.