SvelteKit导入@arcgis/core触发ESM兼容报错 纯Vite运行正常
尝试在SvelteKit项目中接入Esri ArcGIS的NPM包。根据官方文档说明,@arcgis/core为ESM格式包,但按照文档指引在SvelteKit中导入该包时,却触发了CommonJS相关报错。
复现方式
在新建的SvelteKit项目中,将index.svelte修改为如下代码:
<script> import Map from "@arcgis/core/Map"; import MapView from "@arcgis/core/views/MapView"; const map = new Map({ basemap: "arcgis-topographic" // Basemap layer service }); </script>
运行后触发初始报错:
未找到命名导出'setAssetPath'。请求的模块'@esri/calcite-components/dist/components/index.js'是CommonJS模块,可能不支持将所有module.exports作为命名导出。CommonJS模块始终可通过默认导出方式导入,示例用法如下:
import pkg from '@esri/calcite-components/dist/components/index.js'; const {setAssetPath: o} = pkg;
该报错可通过公开沙箱环境复现。
排查过程
- 最初怀疑问题与Vite构建工具有关,参考公开教程在纯Vite项目中导入
@arcgis/core,依赖可正常运行,无任何报错。 - 排查
@arcgis/core依赖的@esri/calcite-components包时,发现其package.json中未配置"type": "module"字段,初步判断是@arcgis/core导入了CommonJS模块。但进一步调试确认,calcite-components是基于Stencil构建的项目,实际包含完整ESM产物,与报错提示的CommonJS模块描述不符。
手动修复后的二次异常
按照初始报错给出的修复建议,手动修改问题文件node_modules/@arcgis/core/widgets/support/componentsUtils.js的导入语句:
// 旧导入语句 // import{setAssetPath as o}from"@esri/calcite-components/dist/components/index.js" // 修改后语句 import pkg from '@esri/calcite-components/dist/components/index.js'; const {setAssetPath: o} = pkg;
修改后初始报错消失,但又在node_modules/@arcgis/core/widgets/support/chartUtils.js文件中触发了新的报错。
该文件首行代码为:
import{chartColorSets as t}from"@esri/calcite-colors";
对应报错内容为:
请求的模块'@esri/calcite-colors'未提供名为'chartColorSets'的导出。
该现象存在明显反常逻辑:calcite-colors本身是标准ESM格式包,确实存在chartColorSets命名导出。删除所有@arcgis/core相关导入,直接将import{chartColorSets as t}from"@esri/calcite-colors"语句写入index.svelte中,代码可正常运行无任何报错。Esri官方论坛上也有其他用户反馈过同类问题。
待确认疑问
- 为何纯Vite项目可正常运行
@arcgis/core依赖,基于Vite的SvelteKit却会触发报错? - 为何SvelteKit仅在通过
@arcgis/core间接导入calcite-colors时提示命名导出不存在,直接导入该包时却可正常运行?
内容的提问来源于stack exchange,提问作者Diesel

