How to install Typescript typings for google maps

前端 未结 12 1041
春和景丽
春和景丽 2020-11-28 04:07

How can it be done - I\'ve tried combinations of

typings install [googlemaps | google.maps] [--ambient] --save

and end up with variations o

相关标签:
12条回答
  • 2020-11-28 04:09

    My solution (works for Vue2.x):

    Install

    npm install --save @types/googlemaps
    

    Add script to index.html

    <script src="https://maps.googleapis.com/maps/api/js?key=XXX&libraries=YYYY"></script>
    

    Create in root folder types/index.d.ts

    Put here the next lines:

    /// <reference path="../node_modules/@types/googlemaps/index.d.ts" />
    declare module 'googlemaps';
    

    Open tsconfig.json and add "types/*.d.ts" to your "include" array.

      "include": [
        "src/**/*.ts",
        "src/**/*.tsx",
        "src/**/*.vue",
        "tests/**/*.ts",
        "tests/**/*.tsx",
        "types/**/*.d.ts"
      ],
    
    0 讨论(0)
  • 2020-11-28 04:10

    So what makes this exceptional is that the maps script needs to be downloaded separately from your app bundle. It's not your typical npm install where you get your .js and .ts nicely packaged for consumption.

    TLDR: the typings can be installed via npm but the .js script must be downloaded via a <script> tag (for SPAs this tag can be appended to your web page on-the-fly to improve initial load time of your app, which is what I do).

    My recommended path is as follows:

    Install

    npm install --save-dev @types/googlemaps
    

    Import

    import {} from 'googlemaps';
    

    Load & Use (this function makes sure the maps script is only appended to the page once, so that it can be called over and over)

    addMapsScript() {
      if (!document.querySelectorAll(`[src="${googleMapsUrl}"]`).length) { 
        document.body.appendChild(Object.assign(
          document.createElement('script'), {
            type: 'text/javascript',
            src: googleMapsUrl,
            onload: () => doMapInitLogic()
          }));
      } else {
        this.doMapInitLogic();
      }
    }
    

    Remember, the maps script must be appended to the page and the script must be downloaded before anything else happens. If you're using Angular, for example, I wrap the addMapsScript() logic in an observable and put in my map components route resolver.

    Use the types (Type definitions include, but are not limited to):

    const mapRef: google.maps.Map;
    const bounds: google.maps.LatLngBounds;
    const latLng: google.maps.LatLng;
    

    Get Rid of the warning:@types/googlemaps/index.d.ts' is not a module.

    Add a file at your projects root directory called index.d.ts and insert the following:

    declare module 'googlemaps';
    


    Update 01.06.2018 (findings of @DicBrus):

    In order to import google namespaces and get rid of annoying error "Cannot find namespace 'google'" you should ensure that you've imported namespace definitions in @types/googlemaps

    There are two ways to do it:

    1. triple-slash directive

      /// /node_modules/@types/googlemaps/index.d.ts" /> Worked fine, but not so elegant.

    Documentation could be found here: https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html

    1. Ensure that it is imported in tsconfig.json and since it is imported you do not need to import something additionally

    Detailed manual is here: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html

    you should check two subsections under compilerOptions: typeRoots and types

    By default all type definitions under node_modules/@types are imported unless you specified exactly what you need.

    In my particular case I had following section:

    "types": []
    

    It disables automatic inclusion of @types packages.

    Removing this line re-solved issue for me, as well also adding triple-slash directive helped. But I chose the second solution.

    As for the "empty" import, I didn't found any explanation how and why it works. I suppose that it does NOT import any module or class, but it does import namespaces. This solution is not suitable for me, since IDE marks this import as "not used" and it can be easily removed. E.g, webstorm's command Ctrl+Alt+O - prettifies code and removes all unnecessary imports.

    0 讨论(0)
  • 2020-11-28 04:11

    I tested these steps on my ionic 2 project and it is works perfectly:

    1. install typings globally :

    npm install typings --global
    
    1. install google.maps via typings

    typings install dt~google.maps --global --save
    
    1. open tsconfig.json and add "typings/*.d.ts" to your "include" array as shown below (tsconfig.json).

    {
      "compilerOptions": {
        "allowSyntheticDefaultImports": true,
        "declaration": false,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "lib": [
          "dom",
          "es2015"
        ],
        "module": "es2015",
        "moduleResolution": "node",
        "sourceMap": true,
        "target": "es5"
      },
      "include": [
        "src/**/*.ts",
        "typings/*.d.ts"
      ],
      "exclude": [
        "node_modules"
      ],
      "compileOnSave": false,
      "atom": {
        "rewriteTsconfig": false
      }
    }
    
    0 讨论(0)
  • 2020-11-28 04:14

    As of typescript 2

    npm install --save @types/googlemaps
    

    Add typeroots to your tsconfig

    {
      "compilerOptions": {
        "typeRoots": ["./node_modules/@types/"]
      }
    }
    
    0 讨论(0)
  • 2020-11-28 04:15

    Stephen Paul clearly explains everything, but there is something important to mention. tsconfigs can extend each other. And extended one can overwrite the parent one. In my case I had another tsconfig.app.json under app directory which has

    types: []
    

    arrays. As Stephen already explained this empty array overrides typeRoots. So just remove all types arrays in ALL related tsconfig files and ensure that

    "typeRoots": ["node_modules/@types"]
    

    is present. Needless to say that @types@googlemaps must be installed

    0 讨论(0)
  • 2020-11-28 04:17

    In practise, my use case is the Angular CLI, and there all I need is

    npm install --save @types/google-maps
    
    0 讨论(0)
提交回复
热议问题