如何为谷歌地图安装 Typescript 类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36064697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to install Typescript typings for google maps
提问by Simon H
How can it be done - I've tried combinations of
怎么做 - 我试过组合
typings install [googlemaps | google.maps] [--ambient] --save
and end up with variations on this error
并最终出现此错误的变化
typings ERR! message Unable to find "googlemaps" for "npm" in the registry.
打字错误!消息无法在注册表中找到“npm”的“googlemaps”。
Per Amy's suggestion, I've also download to the relevant directory and added
根据艾米的建议,我也下载到相关目录并添加
/// <reference path="main/ambient/google.maps/google.maps.d.ts" />
to my main.d.ts
(a file which is clearly being read as I don't get other errors).
到我的main.d.ts
(由于我没有收到其他错误,显然正在读取的文件)。
And I can't find anything on the web to answer the question
而且我在网上找不到任何可以回答问题的内容
My end goal is to get rid of this sort of error
我的最终目标是摆脱这种错误
error TS2503: Cannot find namespace 'google'.
错误 TS2503:找不到命名空间“google”。
回答by Stephen Paul
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.
因此,之所以如此与众不同,是因为地图脚本需要从您的应用程序包中单独下载。这不是您购买并精美包装以供消费的典型npm install
场所。.js
.ts
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).
TLDR:typings可以通过 npm 安装,但 .js 脚本必须通过<script>
标签下载(对于 SPA,这个标签可以即时附加到您的网页以改善您的应用程序的初始加载时间,这就是我做)。
My recommended path is as follows:
我推荐的路径如下:
Install
安装
npm install --save @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.
请记住,地图脚本必须附加到页面,并且必须在发生任何其他事情之前下载脚本。例如,如果您使用的是 Angular,我会将 addMapsScript() 逻辑包装在一个 observable 中,并放入我的地图组件路由解析器中。
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.
摆脱警告:@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:
在您的项目根目录中添加一个名为的文件index.d.ts
并插入以下内容:
declare module 'googlemaps';
Update 01.06.2018 (findings of @DicBrus):
2018 年 6 月 1 日更新(@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
为了导入 google 命名空间并摆脱烦人的错误“找不到命名空间 'google'”,您应该确保已在 @types/googlemaps
There are two ways to do it:
1. triple-slash directive
有两种方法可以做到:
1. 三斜线指令
/// <reference path="<relevant path>/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
文档可以在这里找到:https: //www.typescriptlang.org/docs/handbook/triple-slash-directives.html
- Ensure that it is imported in
tsconfig.json
and since it is imported you do not need to import something additionally
- 确保它是导入的
tsconfig.json
,因为它是导入的,所以你不需要额外导入一些东西
Detailed manual is here: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html
详细手册在这里:https: //www.typescriptlang.org/docs/handbook/tsconfig-json.html
you should check two subsections under compilerOptions
:
typeRoots
and types
您应该检查以下两个小节compilerOptions
:
typeRoots
和types
By default all type definitions under node_modules/@types are imported unless you specified exactly what you need.
默认情况下,node_modules/@types 下的所有类型定义都将被导入,除非您准确指定了您需要的内容。
In my particular case I had following section:
在我的特殊情况下,我有以下部分:
"types": []
It disables automatic inclusion of @types packages.
它禁用@types 包的自动包含。
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 NOTimport 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.
至于“空”导入,我没有找到任何解释它如何以及为什么起作用。我想,它不导入任何模块或类,但它进口的命名空间。此解决方案不适合我,因为 IDE 将此导入标记为“未使用”并且可以轻松删除。例如,webstorm 的命令 Ctrl+Alt+O - 美化代码并删除所有不必要的导入。
回答by Simon H
In practise, my use case is the Angular CLI, and there all I need is
实际上,我的用例是 Angular CLI,我只需要
npm install --save @types/google-maps
回答by user2662006
I tested these steps on my ionic 2 project and it is works perfectly:
我在我的 ionic 2 项目上测试了这些步骤,它完美地工作:
- install typingsglobally :
- 安装分型全球:
npm install typings --global
- install google.maps via typings
- 通过打字安装 google.maps
typings install dt~google.maps --global --save
- open tsconfig.json and add "typings/*.d.ts"to your "include" array as shown below (tsconfig.json).
- 打开 tsconfig.json 并将“typings /*.d.ts”添加到“include”数组中,如下所示(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
}
}
回答by Mike Jerred
typings install google.maps --global
typings install google.maps --global
You need the --global
(used to be --ambient
) flag to search DefinitlyTyped
您需要--global
(曾经是--ambient
)标志来搜索 DefinitlyTyped
回答by Matyas
As of now the correct way to install is:
截至目前,正确的安装方法是:
typings install dt~google.maps --global [--save]
回答by Johansrk
As of typescript 2
截至打字稿2
npm install --save @types/googlemaps
Add typeroots to your tsconfig
将 typeroots 添加到您的 tsconfig
{
"compilerOptions": {
"typeRoots": ["./node_modules/@types/"]
}
}
回答by Andrey Bulgakov
My solution (works for Vue2.x):
我的解决方案(适用于 Vue2.x):
Install
安装
npm install --save @types/googlemaps
Add script to index.html
将脚本添加到 index.html
<script src="https://maps.googleapis.com/maps/api/js?key=XXX&libraries=YYYY"></script>
Create in root folder types/index.d.ts
在根文件夹 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.
打开 tsconfig.json 并将“types/*.d.ts”添加到“include”数组中。
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx",
"types/**/*.d.ts"
],
回答by felixmosh
I struggled to define the google object on the window, finally found a good way, by extending Window
interface.
苦苦在window上定义google对象,终于找到了一个好方法,通过扩展Window
接口。
Just create a google-maps.d.ts
file with this:
只需创建一个google-maps.d.ts
文件:
import '@types/googlemaps';
declare global {
interface Window {
google: typeof google;
}
}
And add it to a directory called types
at your rootfolder.
Then point to this folder in your tsconfig.json
file.
并把它添加到一个名为目录types
在你的根文件夹。然后指向文件中的此文件夹tsconfig.json
。
// tsconfig.json
compilerOptions: {
...
"typeRoots": [
"node_modules/@types",
"types"
],
...
}
回答by Timothy
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
斯蒂芬保罗清楚地解释了一切,但有一些重要的事情要提。tsconfigs 可以相互扩展。并且扩展一个可以覆盖父一个。就我而言,我在 app 目录下有另一个 tsconfig.app.json
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。因此,只需删除所有相关 tsconfig 文件中的所有类型数组并确保
"typeRoots": ["node_modules/@types"]
is present. Needless to say that @types@googlemaps must be installed
存在。不用说必须安装@types@googlemaps
回答by ícaro de Barros
The easyest way is use a triple-slash directive. Fortunately, there's an alternative syntax available which takes advantage of the standard package resolution:
最简单的方法是使用三斜线指令。幸运的是,有一种替代语法可以利用标准包解析:
/// <reference types="googlemaps" />