首页 > 解决方案 > Typescript 中的错误导入

问题描述

我安装了这个包:https://www.npmjs.com/package/@types/googlemaps,创建一个从谷歌地图获取旅行时间的函数,但是在启动后,我的控制台抛出了我:

Error: Cannot find module 'googlemaps'

我尝试像这样导入:

import * as google from 'googlemaps';

但它不起作用,

我也尝试创建index.d.ts

declare module 'googlemaps';

但没有成功,

我的代码:

var google = require('googlemaps'); // another try


  async calculateTravelTime() {
    const directionsService = new google.maps.DirectionsService();
    
    directionsService.route(
        {
            origin: { lat: 37.77, lng: -122.447 },
            destination: { lat: 37.768, lng: -122.511 },
            travelMode: google.maps.TravelMode.DRIVING
        },
        (response, status) => {
            if(status == "OK") {
                console.log(response);
            } else {
                console.log(response);
            }
          }
      )
  }

那么,如何正确导入googlemaps打字稿?

谢谢你的帮助

标签: javascripttypescriptgoogle-mapsgoogle-maps-api-3

解决方案


尝试安装 googlemaps 的类型。

npm install --save @types/googlemaps

然后再试一次

import google from 'googlemaps';

或者

import * as google from 'googlemaps';

推荐阅读