npm 安装 APlayer 融入前端工程
适用场景
npm 安装适合有构建工具的前端项目:
- Vue / React / Svelte 单页应用
- Vite / Webpack / Rollup / Parcel 项目
- TypeScript 工程
- 需要按需裁剪(如 Tree-shaking)
安装
# npm
npm install aplayer --save
# yarn
yarn add aplayer
# pnpm
pnpm add aplayer
安装完成后,node_modules/aplayer/dist/ 下会有 APlayer.min.js 和 APlayer.min.css。
ES Module 引入
import 'APlayer/dist/APlayer.min.css';
import APlayer from 'APlayer';
const ap = new APlayer({
container: document.getElementById('aplayer'),
audio: [{
name: '歌曲名称',
artist: '艺术家',
url: 'audio.mp3',
cover: 'cover.jpg'
}]
});
Vite 项目示例
// src/components/MusicPlayer.vue 或 .jsx
import { onMounted, ref } from 'vue';
// 或 React: import { useEffect } from 'react';
import 'APlayer/dist/APlayer.min.css';
import APlayer from 'APlayer';
export function useAPlayer(containerRef, options) {
let ap = null;
function init() {
ap = new APlayer({
container: containerRef.value,
...options
});
}
function destroy() {
if (ap) {
ap.destroy();
ap = null;
}
}
return { init, destroy };
}
与 HLS 配合
import 'APlayer/dist/APlayer.min.css';
import APlayer from 'APlayer';
import Hls from 'hls.js';
// 注意:需要在全局挂载 Hls,让 APlayer 能检测到
window.Hls = Hls;
const ap = new APlayer({
container: document.getElementById('aplayer'),
audio: [{
name: '直播流',
artist: '来源',
url: 'live.m3u8',
cover: 'cover.jpg',
type: 'hls'
}]
});
TypeScript 类型声明
APlayer 官方没有提供 TypeScript 类型,但有社区维护的类型包:
npm install @types/aplayer --save-dev
或者你可以自己声明一个最简单的:
declare class APlayer {
constructor(options: any);
play(): void;
pause(): void;
seek(time: number): void;
destroy(): void;
list: any;
audio: HTMLAudioElement;
on(event: string, handler: Function): void;
theme(color: string, index?: number): void;
notice(text: string, time?: number, opacity?: number): void;
toggle(): void;
volume(percentage: number, nostorage?: boolean): void;
setMode(mode: 'mini' | 'normal'): void;
version: string;
}
构建产物体积
npm 安装后,Webpack / Vite / Rollup 等构建工具可以自动把 APlayer 打包进项目的 vendor chunk。压缩后体积大约:
- JS:~50KB(原始)/ ~15KB(gzip)
- CSS:~15KB(原始)/ ~4KB(gzip)
CDN vs npm 怎么选
| 对比项 | CDN 引入 | npm 安装 |
|---|---|---|
| 上手速度 | 30 秒 | 几分钟 |
| 需要构建工具 | 不需要 | 需要 |
| 与 Vue/React 配合 | 比较麻烦 | 自然 |
| 版本管理 | URL 里写版本号 | package.json 管理 |
| Tree-shaking | 不支持 | 支持 |
| 离线可用 | 不行 | 可以 |
| 适合场景 | 静态页面 / 快速验证 | 前端工程化项目 |