非React/jQuery环境下Tippy.js+TypeScript使用及报错解决
Tippy.js + TypeScript 正确使用指南与完整示例
问题原因
你遇到的报错是因为当前Tippy.js的类型定义中,默认导出的tippy是一个接口类型而非可调用函数,旧示例的默认导入方式已经不适用于新版本(v6+)。
正确导入方式
改用命名导入获取可调用的tippy函数,同时按需导入类型:
import { tippy, TippyInstance, Props, LifecycleHooks } from 'tippy.js';
完整使用示例
1. 安装依赖
npm install tippy.js npm install -D typescript @types/tippy.js
注:@types/tippy.js是官方维护的类型定义包,确保版本与tippy.js主包匹配。
2. TypeScript配置调整
你的tsconfig.json基本无需修改,只需确保以下关键配置正确:
{ "compilerOptions": { "module": "ES2022", "moduleResolution": "Node16", "esModuleInterop": true, "lib": ["ES2022", "DOM", "DOM.Iterable"], "strict": true }, "include": ["src/**/*"], "exclude": ["node_modules"] }
3. 核心代码示例
基础初始化与自定义配置
// src/main.ts import { tippy, Props, TippyInstance } from 'tippy.js'; // 必须引入样式,否则tooltip无视觉效果 import 'tippy.js/dist/tippy.css'; // 1. 基础用法:批量绑定带data-tippy-content属性的元素 tippy('[data-tippy-content]'); // 2. 自定义配置的单个tooltip const customTooltipProps: Props = { content: '这是自定义提示文本', placement: 'right', animation: 'fade', delay: [300, 100], // 显示延迟300ms,隐藏延迟100ms // 生命周期钩子示例 onShow(instance: TippyInstance) { console.log('Tooltip已显示', instance); }, onHide(instance: TippyInstance) { console.log('Tooltip已隐藏', instance); } }; // 获取目标元素并绑定 const targetBtn = document.getElementById('custom-tooltip-btn'); if (targetBtn) { const tooltipInstance = tippy(targetBtn, customTooltipProps); // 手动控制tooltip(可选) // tooltipInstance.show(); // 主动显示 // tooltipInstance.hide(); // 主动隐藏 // tooltipInstance.destroy(); // 销毁实例 }
配套HTML结构
<!-- index.html --> <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Tippy.js + TS Demo</title> </head> <body> <button data-tippy-content="默认提示内容">默认Tooltip按钮</button> <button id="custom-tooltip-btn">自定义Tooltip按钮</button> <!-- 加载编译后的TS代码 --> <script type="module" src="./dist/main.js"></script> </body> </html>
常见问题排查
- 类型错误:检查
@types/tippy.js与tippy.js的版本是否匹配,卸载后重新安装对应版本 - 样式缺失:确认已正确引入tippy的CSS文件,若使用主题可替换为
tippy.js/themes/light.css等 - 模块解析失败:确保
tsconfig.json的moduleResolution设置为Node16或NodeNext,符合ES模块导入规范
内容的提问来源于stack exchange,提问作者Wizard of Kneup
相关产品推荐
相关产品推荐

