Angular: 使用@types/spotify-web-playback-sdk 时找不到命名空间"Spotify"

Angular: Cannot find namespace "Spotify" when using @types/spotify-web-playback-sdk

我正在尝试在我的 angular 项目中使用 https://www.npmjs.com/package/@types/spotify-web-playback-sdk 在我的组件之一中输入 spotify 播放器。我按照说明安装了类型...

npm install --save @types/spotify-web-playback-sdk

当我定义这个 class 变量并将其输入到 SpotifyPlayer 时,Visual Studio 代码 linter 没有抱怨...

// class variable
spotifyPlayer: Spotify.SpotifyPlayer;

但是,当我去构建我的代码时,我得到了这个错误...

ERROR in src/app/components/header/header.component.ts:32:18 - error TS2503: Cannot find namespace 'Spotify'.

32   spotifyPlayer: Spotify.SpotifyPlayer;

我正在使用...

Angular CLI: 9.1.0
Node: 10.15.1
OS: win32 x64

Angular: 9.1.0
... animations, cli, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router
Ivy Workspace: Yes

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.901.0
@angular-devkit/build-angular     0.901.0
@angular-devkit/build-optimizer   0.901.0
@angular-devkit/build-webpack     0.901.0
@angular-devkit/core              9.1.0
@angular-devkit/schematics        9.1.0
@ngtools/webpack                  9.1.0
@schematics/angular               9.1.0
@schematics/update                0.901.0
rxjs                              6.5.4
typescript                        3.8.3
webpack                           4.42.0

感谢您的帮助!

您必须在每个 class 中导入命名空间 例如import * as Spotify from 'Spotify'

根据类型定义 here spotify-web-playback-sdknon-npm package。 根据 Spotify 文档 here,您将直接在 html 中添加 JS bundle,这意味着此 Script 不会作为 [=17] 加载=].

来自DefinitelyTyped

You may need to add a types reference if you're not using modules

您可以将以下行添加到您正在使用 Spotify namespace 的文件顶部,错误应该会消失。

///  <reference types="@types/spotify-web-playback-sdk"/>

更多信息是here and here。每当 Spotify 发布 npm 库时,更喜欢使用它。