使用 Vue 3 + typescript + vite。
已使用 Vite + Vue 3 + typescript 建立项目。 使用谷歌地图时遇到问题,因为它需要付费。 于是尝试了 Mapbox, map 部分工作正常,但在添加 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
现在可以正常使用了!希望它也对您有用。
关于typescript - 类型错误 : EventEmitter is not a constructor at new MapboxGeocoder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69717406/