網站搜尋

javascript - 在 Angular 14/15 中使用 MUX 播放器(影片)


Mux 是一個視頻 API 服務,擁有自己的播放器:MUX Player

我想在 Angular 14/15 中使用這個 npm 套件,僅將它匯入到特定的元件中。只有在這個元件被載入時,這個 js 才會被載入。

導入

使用該服務的兩種方法是:

  1. 透過在 HTML 中直接 <script src="https://unpkg.com/@mux/mux-player"></script> 的匯入(我可以在 Angular 的 index.html 文件中這樣做)。不過這意味著腳本會對所有人加載,這不是我想要的。
  2. npm 套件 @mux/mux-player

使用

將代碼添加到已導入腳本或 npm 套件的組件 HTML 中。

<mux-player
stream-type="on-demand"
playback-id="FuJSYrK0014ec2LPnm11bzC2MAySAQPqA"
metadata-video-title="Tea and Cookies"
metadata-user-id="user-24601"
/>

確保在模組(或獨立元件)中也包括 schemas: [CUSTOM_ELEMENTS_SCHEMA]。

問題

Angular 對於未類型化的套件可能會有點奇怪。我認為這個套件使用 TypeScript,但無論如何,導入這個 npm 套件會給我帶來很多錯誤。基本上,它沒有被加載,因為當我在元件的 ts 中沒有使用導入的類時,Angular 會將其進行 tree-shaking。這意味著在加載時,我看到:Cannot find module '../../../types/mux' or its corresponding type declarations 和 Property 'error' in type 'MuxVideoElement' is not assignable to the same property in base type 'CustomVideoElement<HTMLVideoElement>'. Type 'MediaError' is missing the following properties from type 'MediaError': MEDIA_ERR_ABORTED, MEDIA_ERR_DECODE, MEDIA_ERR_NETWORK, MEDIA_ERR_SRC_NOT_SUPPORTED

我嘗試過的

  1. 為了確認 <script> 的匯入與 HTML 代碼能正常協作,我將該腳本匯入到 index.html,這樣就消除了所有錯誤,播放器也能正常載入。

  2. 我已經嘗試導入 npm 套件 import MuxPlayerElement from "@mux/mux-player";,並且在 typings.d.ts 中添加了 declare module "@mux/mux-player";。

  3. 將套件匯入到組件中,並嘗試將 @ViewChild 模板引用宣告為 MuxPlayerElement,以迴避任何樹搖優化。

在 https://www.mux.com/player 上有一個 Angular 範例,其中顯示「This player? It's an open book.」,但這會導致錯誤 Only void and foreign elements can be self closed "mux-player"。簡單的解決方法是使用 </mux-player> 來關閉標籤,而不是用 .../>。

答案#1

更新!

Mux 在 1.9.0 中處理了 Angular 支援

https://docs.mux.com/guides/player/releases#190

使用說明:

  1. npm install @mux/mux-player
  2. 將 schemas: [CUSTOM_ELEMENTS_SCHEMA] 添加到模組(或獨立元件)
  3. 將 import "@mux/mux-player" 添加到目標組件的導入中
  4. 按照文件使用 <mux-player ...></mux-player>

🎉