Next.js项目中使用lottie-player重复注册自定义元素报错求助
问题根源
你同时通过两种方式引入了lottie-player:useEffect动态导入本地npm包和页面内script标签引入CDN版本,这两个操作都会向CustomElementRegistry注册<lottie-player>自定义元素,导致重复注册触发报错。
解决方案(二选一即可)
方案一:仅使用本地npm包(推荐)
- 直接删除页面中的
<script>标签,无需重复引入CDN版本 - 优化useEffect的导入逻辑,添加空依赖数组确保只执行一次:
import { useEffect } from 'react'; useEffect(() => { const loadLottie = async () => { try { await import('@lottiefiles/lottie-player'); } catch (err) { console.error('lottie-player加载失败:', err); } }; loadLottie(); }, []); // 空依赖数组保证仅组件挂载时执行一次
- 保留
<lottie-player>标签正常使用即可
额外优化(适配Next.js SSR特性)
由于自定义元素在服务端渲染时可能出现兼容性问题,可将包含lottie-player的组件改为动态导入并禁用SSR:
import dynamic from 'next/dynamic'; // 假设你的lottie组件放在components/LottieIcon.js const LottieIcon = dynamic(() => import('../components/LottieIcon'), { ssr: false, loading: () => <div>动画加载中...</div> }); // 在页面中使用 <LottieIcon />
方案二:仅使用CDN引入
- 卸载本地安装的包:
npm uninstall @lottiefiles/lottie-player
- 删除useEffect中的动态导入代码
- 将script标签移至
_document.js或_app.js中,确保全局只加载一次:
// _document.js示例 import Document, { Html, Head, Main, NextScript } from 'next/document'; class MyDocument extends Document { render() { return ( <Html> <Head> <script src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js" async defer ></script> </Head> <body> <Main /> <NextScript /> </body> </Html> ); } } export default MyDocument;
内容的提问来源于stack exchange,提问作者Munir Sami Nuristani
相关产品推荐
相关产品推荐

