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

问题描述 投票:14回答:4

这个问题在很多地方只需添加解决方案,就出现了类似的问题

import { } from '@types/googlemaps';

在过去的angular版本中作为解决方案。现在出现问题,因为我正在使用Angular 6+

TS2304: Cannot find name 'google'.
TS2503: Cannot find namespace 'google'.

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

let place: google.maps.places.PlaceResult = autocomplete.getPlace();

我可以通过在使用Google Maps的所有行上方插入// @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"
    ]
  }
}

我创建了一个Stackblitz Example,如果您查看控制台,它将引发参考错误。我不知道下一步该怎么做。

angular typescript namespaces tsconfig
4个回答
24
投票

所以我在github上遇到了这个问题,这对我有用

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

  • 添加到我的所有tsconfig * .json中:类型:[“ googlemaps”]

  • 在文件的顶部添加:声明const google:任何;

  • 在我的index.html正文末尾添加:

script>

尝试一下,告诉我是否可行


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"]
}

4
投票

将其添加到我的tsconfig编译器选项的types数组中从未成功。但是,如果您安装了@ types / googlemaps,则可以使用以下代码在.ts文件的顶部引用:

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

cf。 Triple Slash Directives


3
投票

我发现了一些东西,如果您使用的是AGM,可以修复其导入:

import {} from '@agm/core/services/google-maps-types';
© www.soinside.com 2019 - 2024. All rights reserved.