启动新实例时未找到加载模块的 ES6 依赖项(未捕获类型错误)

问题描述 投票:0回答:1

我正在学习 JS,由于我普遍缺乏知识,我自己似乎找不到正确的关键字来谷歌解决方案。

我正在尝试将 Leaflet 作为应用程序的一部分加载,该应用程序是使用 ES6 模块构建的。 文件结构:

- Home directory
    - index.html
    - /scripts
         - main.js
         - /app
             - mapApp.js
         - /lib
             - leaflet.js

index.html 内

    ...
    <script type="module" src="scripts/main.js"></script>
</head>
<body>
    <div id="app"></div>
    ...

mapApp 包含一个对象,该对象将被扩展为包含更改地图/gui 的方法。在其最基本的布局中,mapApp.js 包含:

import * as L from "../lib/leaflet/leaflet.js"

function mapApp(container){

    // Fixed values
    var bounds = [
        [50.769562,5.448265], // Southwest coordinates
        [50.801687,5.507624] // Northeast coordinates
    ];

    // Parameters

    this.container = container  

    // Map initialize
    this.map = L.map(this.container,{
        zoomControl:false,
        maxZoom:21, 
        minZoom:8,
        center:[50.78898,5.4889],
        zoom:14,
        maxBounds: bounds,
        maxBoundsViscosity: 1.0 // Prevents pushback behaviour at bounds
    });
};

最后在 main.js 中,这可能会创建 mapApp 的多个实例:

import {mapApp} from "./app/mapApp.js";

tester = new mapApp('app')

对于最后一行(测试者 = ...),我得到了

Uncaught TypeError: L.map is not a function

我可以通过在 main.js 中再次导入 leaflet 来解决这个问题。但这似乎不是正确的方法?我必须在整个程序链中重新加载“子/嵌套”导入,这似乎很麻烦?

我不明白什么?

javascript leaflet es6-modules
1个回答
0
投票

经过一段可笑的时间我终于解决了。

我一定在某个地方加载了“L”库,这让我更加困惑。

事实证明,缩小的传单(leaflet.js)不能用于模块。请改用 leaflet-src.ecm.js 文件。另请参阅此问题,了解有关 .ecm 格式的更多详细信息。

对于其他有此问题或类似问题的人,我建议也使用这个SO问题中的解决方案,并尝试直接从控制台加载模块。一旦它在那里工作,你就可以开始了(除非像我一样,你对错误加载的具有相同缩写的库感到困惑)

TL;DR:解决方案是将

import * as L from "../lib/leaflet/leaflet.js"
更改为正确的文件,支持模块:
import * as L from "../lib/leaflet/leaflet-src.esm.js"

© www.soinside.com 2019 - 2024. All rights reserved.