Coder Social home page Coder Social logo

haidarz / esri-loader Goto Github PK

View Code? Open in Web Editor NEW

This project forked from esri/esri-loader

1.0 0.0 0.0 432 KB

A tiny library to help load ArcGIS API for JavaScript modules in non-Dojo applications

License: Apache License 2.0

TypeScript 89.84% JavaScript 8.87% Shell 1.29%

esri-loader's Introduction

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, React 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 Modules from the ArcGIS API for JavaScript

From the Latest Version

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

import { loadModules } from 'esri-loader';

// first, we use Dojo's loader to require the map class
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);
  });

From a Specific Version

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.

import { loadModules } from 'esri-loader';

// if the API hasn't already been loaded (i.e. the first 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 = { version: '3.30' };

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);
  });

You can load the "next" version of the ArcGIS API by passing next as the version.

From a Specific URL

You can also load the modules from a specific URL, for example from a version of the SDK that you host on your own server. In this case, instead of passing the version option, you would pass the URL as a string like:

const options = { url: `http://server/path/to/esri` };

Lazy Loading the ArcGIS API for JavaScript

Lazy loading the ArcGIS API can dramatically improve the initial load performance of your application, especially if your users may never end up visiting any routes that need to show a map or 3D scene. That is why it is the default behavior of esri-loader. In the above snippets, the first time loadModules() is called, it will attempt lazy load the ArcGIS API by calling loadScript() for you. Subsequent calls to loadModules() will not attempt to load the script once loadScript() has been called.

See below for information on how you can pre-load the ArcGIS API after initial render but before a user visits a route that needs it.

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. Just like the ArcGIS API modules, you'll probably want to lazy load the styles only once they are needed by the application.

When you load the script

The easiest way to do that is to pass the css option to loadModules() or loadScript():

import { loadModules } from 'esri-loader';

// before loading the modules for the first time, 
// also lazy load the CSS for the version of 
// the script that you're loading from the CDN 
const options = { css: true };

loadModules(['esri/views/MapView', 'esri/WebMap'], options)
  .then(([MapView, WebMap]) => {
    // the styles, script, and modules have all been loaded (in that order)
  });

Passing css: true does not work when loading the script using the url option. In that case you'll need to pass the URL to the styles like: css: 'http://server/path/to/esri/css/main.css'.

When passing the css option to loadModules() it actually passes it to loadScript(), So you can also use the same values (either true or stylesheet URL) when you call loadScript() directly.

Using loadCss()

Alternatively, you can use the provided loadCss() function to load the ArcGIS styles at any point in your application's life cycle. For example:

import { loadCss } from 'esri-loader';

// by default loadCss() loads styles for the latest 4.x version
loadCss();

// or for a specific CDN version
loadCss('3.30');

// or a from specific URL, like a locally hosted version
loadCss('http://server/path/to/esri/css/main.css');

See below for information on how to override ArcGIS styles that you've lazy loaded with loadModules() or loadCss().

Using traditional means

Of course, you don't need to use esri-loader to load the styles. See the ArcGIS API for JavaScript documentation for more information on how to load the ArcGIS styles by more traditional means such as adding <link> tags to your HTML, or @import statements to your CSS.

Why is this needed?

Unfortunately, you can't simply npm install the ArcGIS API and then import 'esri' 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 have been a few different solutions to this problem over the years, but only the @arcgis/webpack-plugin and esri-loader allow you to improve your application's initial load performance, especially on mobile, by lazy loading the ArcGIS API and modules only when they're needed (i.e. to render a map or 3D scene).

This blog post explains why you would choose one or the other of those solutions, but here's the TLDR:

  • Are you using ArcGIS API >= v4.7?
  • Are you using webpack?
  • Are you (willing and) able to configure webpack?

If you answered "Yes" to all those questions you can use @arcgis/webpack-plugin in your application and get the benefits of being able to use import statements and types for 'esri' modules.

Otherwise, you should use esri-loader, which allows you to use the ArcGIS API:

Examples

Here are some applications and framework-specific wrapper libraries that use this library. We don't guarantee 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 favorites here ๐Ÿ˜œ:

Reusable libraries for Angular

Example Angular applications

  • can-arcgis - CanJS configurable mapping app (inspired by cmv-app) and components built for the ArcGIS JS API 4.x, bundled with StealJS
  • esri-choo-example - An example Choo application that shows how to use esri-loader to create a custom map view.
  • dojo-esri-loader - Dojo 5 app with esri-loader (blog post)

  • 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.

  • 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

See the examples over at ember-esri-loader

  • esri-hyperapp-example - An example Hyperapp application that shows how to use esri-loader to create a custom map view and component.
  • ionic2-esri-map - Prototype app demonstrating how to use Ionic 3+ with the ArcGIS API for JavaScript
  • esri-preact-pwa - An example progressive web app (PWA) using the ArcGIS API for JavaScript built with Preact

Reusable libraries for React

Example React applications

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

Advanced Usage

ArcGIS Types

This library doesn't make any assumptions about which version of the ArcGIS API you are using, so you will have to install the appropriate types. Furthermore, because you don't import esri modules directly with esri-loader, you'll have to follow the instructions below to use the types in your application.

4.x Types

Follow these instructions to install the 4.x types.

After installing the 4.x types, you can use the __esri namespace for the types as seen in this example.

3.x Types

You can use these instructions to install the 3.x types.

The __esri namespace is not defined for 3.x types, but you can import * as esri from 'esri'; to use the types as shown here.

TypeScript import()

TypeScript 2.9 added a way to import() types which allows types to be imported without importing the module. For more information on import types see this post. You can use this as an alternative to the 4.x _esri namespace or import * as esri from 'esri' for 3.x.

After you've installed the 4.x or 3.x types as described above, you can then use TypeScript's import() like:

// define a type that is an array of the 4.x types you are using
// and indicate that loadModules() will resolve with that type
type MapModules = [typeof import("esri/WebMap"), typeof import("esri/views/MapView")];
const [WebMap, MapView] = await (loadModules(["esri/WebMap", "esri/views/MapView"]) as Promise<MapModules>);
// the returned objects now have type
const webmap = new WebMap({portalItem: {id: this.webmapid}});

A more complete 4.x sample can be seen here.

This also works with the 3.x types:

// define a type that is an array of the 3.x types you are using
// and indicate that loadModules() will resolve with that type
type MapModules = [typeof import("esri/map"), typeof import("esri/geometry/Extent")];
const [Map, Extent] = await (loadModules(["esri/map", "esri/geometry/Extent"], options) as Promise<MapModules>);
// the returned objects now have type
let map = new Map("viewDiv"...

A more complete 3.x sample can be seen here.

Types in Angular CLI Applications

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.

Using Classes Synchronously

Let's say you need to create a map in one component, and then later in another component add a graphic to that map. Unlike creating a map, creating a graphic and adding it to a map is ordinarily a synchronous operation, so it can be inconvenient to have to wait for loadModules() just to load the Graphic class. One way to handle this is have the function that creates the map also load the Graphic class before its needed. You can then hold onto that class for later use to be exposed by a function like addGraphicToMap(view, graphicJson):

// utils/map.js
import { loadModules } from 'esri-loader';

// NOTE: module, not global scope
let _Graphic;

// this will be called by the map component
export function loadMap(element, mapOptions) {
  // NOTE: 
  return loadModules(['esri/Map', 'esri/views/MapView', 'esri/Graphic'], {
    css: true
  }).then(([Map, MapView, Graphic]) => {
    // hold onto the graphic class for later use
    _Graphic = Graphic;
    // create the Map
    const map = new Map(mapOptions);
    // return a view showing the map at the element
    return new MapView({
      map,
      container: element
    });
  });
}

// this will be called by the component that needs to add the graphic to the map
export function addGraphicToMap(view, graphicJson) {
  // make sure that the graphic class has already been loaded
  if (!_Graphic) {
    throw new Error('You must load a map before creating new graphics');
  }
  view.graphics.add(new _Graphic(graphicJson));
}

You can see this pattern in use in a real-world application.

See #124 (comment) and #71 (comment) for more background on this pattern.

Configuring Dojo

You can pass a dojoConfig option to loadModules() or loadScript() 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.

import { loadModules } from 'esri-loader';

// 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'
      }
    ]
  }
};

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);
  });

Overriding ArcGIS Styles

If you want to override ArcGIS styles that you have lazy loaded using loadModules() or loadCss(), you may need to insert the ArcGIS styles into the document above your custom styles in order to ensure the rules of CSS precedence are applied correctly. For this reason, loadCss() accepts a selector (string) as optional second argument that it uses to query the DOM node (i.e. <link> or <script>) that contains your custom styles and then insert the ArcGIS styles above that node. You can also pass that selector as the insertCssBefore option to loadModules():

import { loadModules } from 'esri-loader';

// lazy load the CSS before loading the modules
const options = {
  css: true,
  // insert the stylesheet link above the first <style> tag on the page
  insertCssBefore: 'style'
};

// before loading the modules, this will call:
// loadCss('https://js.arcgis.com/4.12/themes/light/main.css', 'style')
loadModules(['esri/views/MapView', 'esri/WebMap'], options);

Alternatively you could insert it before the first <link> tag w/ insertCssBefore: 'link[rel="stylesheet"]', etc.

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:

import { loadScript, loadModules } from 'esri-loader';

// 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 = 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
    // by using loadModules()
  })
  .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 library, 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:

import { loadScript } from 'esri-loader';

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

Using your own script tag

It is possible to use this library only to load modules (i.e. not to lazy load or pre-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/4.11/" data-esri-loader="loaded"></script>

Using the esriLoader Global

Typically you would install the esri-loader package and then import the functions you need as shown in all the above examples. However, esri-loader is also distributed as an ES5 UMD bundle on UNPKG so that you can load it via a script tag and use the above functions from the esriLoader global.

<script src="https://unpkg.com/esri-loader"></script>
<script>
  esriLoader.loadModules(['esri/views/MapView', 'esri/WebMap'])
  .then(([MapView, WebMap]) => {
    // use MapView and WebMap classes as shown above
  });
</script>

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 browsers 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 execute requests to ArcGIS REST services from something like a Node.js CLI application, see arcgis-rest-js.

Promises

Since v1.5 asynchronous functions like loadModules() and loadScript() return Promises, so if your application has to support browsers 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.

import { utils } from  'esri-loader';

init () {
  this._super(...arguments);
  // have esriLoader use Ember's RSVP promise
  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 ยฉ 2016-2019 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

https://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.

esri-loader's People

Contributors

alexurquhart avatar andygup avatar davetimmins avatar davewilton avatar davidpiesse avatar deskoh avatar dzeneralen avatar ecaldwell avatar gavinr avatar guzhongren avatar jameslmilner avatar jgravois avatar jwasilgeo avatar lomash avatar remotesc2 avatar richorama avatar ssylvia avatar stdavis avatar thekeithstewart avatar tomwayson avatar ziveo avatar

Stargazers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.