Angular组件无法导入google-one-tap类型,求正确导入方法
解决Angular里google-one-tap类型定义用不了的问题
1. 先确认装的是正确的类型包
得安装官方维护的@types/google-one-tap,执行这条命令:
npm install @types/google-one-tap --save-dev
2. 通过CDN引入全局脚本
google-one-tap不是可直接import的npm模块,必须通过CDN加载全局脚本:
- 打开项目根目录的
angular.json,找到build.options.scripts数组,添加CDN链接:
"scripts": [ "https://accounts.google.com/gsi/client" ]
3. 组件中直接使用全局google变量
不需要写import * as google from 'google-one-tap';这种语句,直接调用全局的google变量即可,类型定义会自动提供代码提示,示例代码:
ngOnInit() { google.accounts.id.initialize({ client_id: '你的Google客户端ID', callback: (response) => { // 处理登录回调逻辑 console.log(response); } }); google.accounts.id.renderButton( document.getElementById('google-login-button'), { theme: 'outline', size: 'large' } // 自定义登录按钮样式 ); }
4. 可选:手动声明类型(若提示异常)
如果安装类型包后仍无类型提示,可在组件顶部手动添加类型声明:
declare const google: typeof import('google-one-tap');
内容的提问来源于stack exchange,提问作者Liam
相关产品推荐
相关产品推荐

