因此,让这一点与众不同的是, map 脚本需要从应用程序包中单独下载.这不是典型的npm install
,你可以把.js
和.ts
包装得很好,以供消费.
TLDR:打字可以通过npm安装,但是.js脚本必须通过一个<script>
标签下载(对于SPA来说,这个标签可以动态添加到你的网页上,以缩短你的应用程序的初始加载时间,我就是这么做的).
我推荐的路径如下:
Install
npm install --save-dev @types/googlemaps
Import
import {} from 'googlemaps';
Load & Use(此函数确保maps脚本只附加到页面一次,以便反复调用)
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(类型定义包括但不限于):
const mapRef: google.maps.Map;
const bounds: google.maps.LatLngBounds;
const latLng: google.maps.LatLng;
Get Rid of the warning:100
在项目根目录中添加一个名为index.d.ts
的文件,并插入以下内容:
declare module 'googlemaps';
Update 01.06.2018 (findings of @DicBrus):
为了导入google名称空间并消除恼人的错误"找不到名称空间‘google’",您应该确保您已经在@types/googlemaps
中导入了名称空间定义
有两种方法:
三斜杠指令
/// /node_modules/@types/googlemaps/index.d.ts" />
Worked fine, but not so elegant.
文件可以在这里找到:https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html
- 确保它是在
tsconfig.json
中导入的,因为它是导入的,所以不需要另外导入某些内容
详细手册如下:https://www.typescriptlang.org/docs/handbook/tsconfig-json.html
你应该勾选compilerOptions
下的两个小节:
默认情况下,将导入 node _modules/@types下的所有类型定义,除非您准确指定了所需的内容.
在我的特殊情况下,我有以下部分:
"types": []
它禁止自动包含@types包.
Removing this line re-solved issue for me, as well also adding 三斜杠指令 helped. But I chose the second solution.
至于"空"导入,我没有找到任何解释它是如何工作的以及为什么工作的.我想它确实导入了任何模块或类,但它确实导入了名称空间.此解决方案不适合我,因为IDE将此导入标记为"未使用",并且可以轻松删除.例如,webstorm的命令Ctrl+Alt+O-美化代码并删除所有不必要的导入.