TypeError:EventEmitter不是新MapboxGeocoder的构造函数

使用Vue 3+打字+Vite。

用VITE+VUE 3+打字稿设置了项目。 使用谷歌地图有问题,因为它需要付费。 于是尝试了Mapbox,地图部分工作正常,但在添加MapboxGeocoder时显示错误。

收到此错误

TypeError: EventEmitter is not a constructor
    at new MapboxGeocoder (index.js:74)
    at temp.vue:30
    at callWithErrorHandling (runtime-core.esm-bundler.js:6668)
    at callWithAsyncErrorHandling (runtime-core.esm-bundler.js:6677)
    at Array.hook.__weh.hook.__weh (runtime-core.esm-bundler.js:1931)
    at flushPostFlushCbs (runtime-core.esm-bundler.js:6869)
    at render2 (runtime-core.esm-bundler.js:4807)
    at mount (runtime-core.esm-bundler.js:3140)
    at Object.app.mount (runtime-dom.esm-bundler.js:1572)
    at main.ts:16

如何解决此错误。需要帮助。

代码块

<script setup lang="ts">
import mapboxgl from "mapbox-gl";
import MapboxGeocoder from "@mapbox/mapbox-gl-geocoder";
import "@mapbox/mapbox-gl-geocoder/dist/mapbox-gl-geocoder.css";

onMounted(() => {
  try {
    mapboxgl.accessToken =
      "TOKEN";

    const map = new mapboxgl.Map({
      container: "map", // container ID
      style: "mapbox://styles/mapbox/streets-v11", // style URL
      center: [-74.5, 40], // starting position [lng, lat]
      zoom: 9, // starting zoom
    });
    map.addControl(
      new MapboxGeocoder({
        accessToken: mapboxgl.accessToken,
       
      })
    );

  } catch (error) {
    console.log("Error on mapbox creation: ", error);
  }
});
</script>


解决方案

我遇到了与Vanilla JS和Vite非常类似的问题。

在深入研究VITE的问题时,我发现:https://github.com/vitejs/vite/issues/2694#issuecomment-826195660这对我很有效。也许更有见识的人将能够准确地解释正在发生的事情。我想有些错误需要在Mapbox中解决--gl、vite或两者兼而有之。

无论如何,我做到了:

npm i events
npm i --save-dev @types/events @types/node

现在它起作用了!希望它也适用于您。

相关文章