Angular 6应用程序找不到命名空间'google'

Mur*_*hy4 14 namespaces typescript tsconfig angular

这个问题在解决方案简单添加的许多地方也出现过类似的问题

import { } from '@types/googlemaps';
Run Code Online (Sandbox Code Playgroud)

这是过去版本的角度解决方案.现在出现的问题是我使用的是Angular 6+

TS2304: Cannot find name 'google'.
TS2503: Cannot find namespace 'google'.
Run Code Online (Sandbox Code Playgroud)

有很多这样的错误,但它发生在每一行,如:

let place: google.maps.places.PlaceResult = autocomplete.getPlace();
Run Code Online (Sandbox Code Playgroud)

我可以通过插入// @ts-ignore使用谷歌地图的所有行来快速解决问题,但我对真正的修复更感兴趣.但是这个有用的事实让我觉得这是一个tsconfig问题,我对此并不十分自信.

我可以确认googlemaps是安装在node_modules/@ types中的,但是

ts.config

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es6",
    "typeRoots": [
      "node_modules/@types",
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个Stackblitz示例,如果您查看控制台,则会引发参考错误.我不知道下一步该尝试什么.

小智 24

所以我早些时候在github上遇到过这个问题,这对我有用

  • npm install --save-dev @ types/googlemaps

  • 添加到我的所有tsconfig*.json:types:["googlemaps"]

  • 在我的文件顶部添加:declare const google:any;

  • 在我的index.html的主体末尾添加:

<script async defer type ="text/javascript"src ="https://maps.googleapis.com/maps/api/js?key=****"> </ script>

尝试一下,告诉我它是否有效

  • 我只是看着我的tsconfig.json,通过在我的tsconfig.app.json中添加"googlemaps",突然间它很高兴.无法相信我无处可寻!干杯 (5认同)

Mar*_*gen 7

将它添加到我的 tsconfig 编译器选项的 types 数组中从未奏效。但是如果你安装了@types/googlemaps,你可以在你的 .ts 文件的顶部使用:

/// <reference types="@types/googlemaps" />

参见 三重斜线指令


Mab*_*ani 7

我通过安装@types/google-maps而不是 @types/googlemaps 来修复它

只需运行这个

npm install @types/google-maps --save
Run Code Online (Sandbox Code Playgroud)

并使用在您的组件中导入 google

import { google } from "google-maps";
Run Code Online (Sandbox Code Playgroud)


小智 6

真正需要更新的tsconfig.json文件位于src / tsconfig.app.json中。

该文件会使用空数组覆盖根目录下tsconfig.json文件的tsconfig.json文件的editorOptions的types属性,因此您必须在其中添加googlemaps的类型定义。

例如:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": ["googlemaps"]
  },
  "exclude": ["test.ts", "**/*.spec.ts"]
}
Run Code Online (Sandbox Code Playgroud)