Angular5项目中使用@types/arcgis-js-api遇__esri未定义错误求助
__esri is not defined的问题 我来帮你排查并解决这个报错问题,核心原因是你对ArcGIS API的类型定义使用方式和异步加载机制的配合出现了问题,下面是一步步的解决方案:
步骤1:确保安装了正确的类型定义依赖
首先确认你已经安装了ArcGIS JS API的官方类型包,没有的话先执行:
npm install @types/arcgis-js-api --save-dev
步骤2:检查TypeScript配置的正确性
你已经在tsconfig.app.json的types数组中添加了arcgis-js-api,请确保配置格式正确,同时确认tsconfig.json的typeRoots默认指向node_modules/@/types(默认配置已包含,无需额外修改):
tsconfig.app.json示例:
{ "compilerOptions": { "types": [ "arcgis-js-api" ] } }
步骤3:修正组件中的代码写法(关键)
你当前使用import Esri = __esri;的方式会触发运行时错误,因为__esri是@types/arcgis-js-api声明的全局命名空间,不需要手动导入,且直接引用会导致API未加载前就访问全局变量的问题。正确的写法是利用esri-loader的异步加载机制,结合类型注解使用:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core'; import * as esriLoader from 'esri-loader'; import { environment } from '../../../environments/environment'; // 无需手动导入__esri,@types已全局声明该命名空间 @Component({ selector: 'your-map-component', template: '<div #mapContainer style="width:100%;height:400px;"></div>' }) export class YourMapComponent implements OnInit { @ViewChild('mapContainer', { static: true }) mapContainer: ElementRef; // 使用__esri命名空间做类型注解(仅编译时生效,不会影响运行时) private map: __esri.Map; private mapView: __esri.MapView; ngOnInit(): void { // 先异步加载ArcGIS JS API esriLoader.load({ url: environment.arcgisApiUrl // 示例:'https://js.arcgis.com/4.24/' }).then(() => { // 加载需要的地图模块 return esriLoader.loadModules(['esri/Map', 'esri/views/MapView']); }).then(([Map, MapView]) => { // 通过加载的模块创建实例,而非直接访问全局__esri this.map = new Map({ basemap: 'topo-vector' }); this.mapView = new MapView({ container: this.mapContainer.nativeElement, map: this.map, center: [-98.5795, 39.8283], zoom: 4 }); this.mapView.when(() => { console.log('地图视图初始化完成'); }); }).catch(error => { console.error('ArcGIS API加载失败:', error); }); } }
关键问题说明
为什么
__esri is not defined?
你之前的写法可能在运行时直接访问了全局的__esri对象(比如new __esri.Map()),但此时ArcGIS API还未通过esri-loader异步加载完成,全局的__esri变量还未挂载,因此触发错误。正确做法是通过esriLoader.loadModules获取模块后再创建实例。类型注解的作用
__esri.Map这类类型仅在TypeScript编译阶段做类型检查,编译后会被完全移除,不会出现在运行时代码中,因此只要类型定义配置正确,就不会触发运行时错误。
如果问题仍然存在,可以尝试:
- 执行
ng clean清除Angular缓存后重新构建项目 - 确认
environment.ts中的ArcGIS API地址可正常访问 - 检查代码中是否有其他误写的运行时访问
__esri的逻辑
内容的提问来源于stack exchange,提问作者Bharath Konaganti




