You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js项目Lottie动画本地正常,部署Vercel后加载失败求助

Next.js项目Vercel部署后Lottie动画加载失败的解决方案
  • 检查静态资源存放位置与引用路径
    Next.js要求静态资源(如Lottie的JSON文件)需放在项目根目录的public文件夹下。如果动画文件存放在src/animations这类非public目录,本地开发环境可能能正常加载,但部署到Vercel后会因资源未被正确打包导致404错误。
    调整步骤:

    1. 将所有Lottie JSON文件移动到public/animations目录
    2. 在代码中通过绝对路径引用,示例:
      import Lottie from 'lottie-react';
      import animationData from '/animations/your-animation.json';
      
      // 或使用lottie-web的loadAnimation方法时指定路径:
      lottie.loadAnimation({
        container: document.getElementById('lottie-container'),
        path: '/animations/your-animation.json',
        renderer: 'svg',
        loop: true,
        autoplay: true
      });
      
  • 修正文件大小写问题
    Vercel运行在Linux环境,文件名严格区分大小写;而本地Windows/macOS系统不区分大小写。如果代码中引用的文件名和实际文件的大小写不一致(比如代码写animation.json,实际文件是Animation.json),本地能正常加载,但部署后会返回404。
    解决:统一代码中的文件名引用和实际文件的大小写,保持完全一致。

  • 调整JSON文件的Webpack打包配置
    如果直接import JSON文件到组件中,Next.js在生产构建时可能需要额外配置以确保JSON被正确打包。在next.config.js中添加如下配置:

    /** @type {import('next').NextConfig} */
    const nextConfig = {
      webpack: (config) => {
        config.module.rules.push({
          test: /\.json$/,
          type: 'asset/resource',
          generator: {
            filename: 'animations/[name][ext]'
          }
        });
        return config;
      }
    };
    
    module.exports = nextConfig;
    

    配置后,import的JSON文件会被打包到public/animations目录下,确保部署后可正常访问。

  • 使用动态加载避免构建时路径问题
    若上述方法无效,可尝试在客户端运行时动态加载Lottie动画数据:

    import { useEffect, useRef } from 'react';
    import lottie from 'lottie-web';
    
    function LottieAnimation() {
      const containerRef = useRef(null);
    
      useEffect(() => {
        if (containerRef.current) {
          fetch('/animations/your-animation.json')
            .then(res => res.json())
            .then(animationData => {
              lottie.loadAnimation({
                container: containerRef.current,
                animationData: animationData,
                renderer: 'svg',
                loop: true,
                autoplay: true
              });
            });
        }
      }, []);
    
      return <div ref={containerRef}></div>;
    }
    
    export default LottieAnimation;
    

内容的提问来源于stack exchange,提问作者Nelson Uprety

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 19:37:22