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

Next13 Beta中导入Lottie JSON动画报错:无法找到模块

解决lottie-react导入本地JSON动画的模块找不到及类型声明错误

一、修正文件导入路径

根据动画文件的存放位置,选择对应的导入方式:

  • 文件放在src目录下(如src/animations/loading-spinner.json):
    导入路径需匹配当前组件与动画文件的相对层级,比如组件在src/components/Loading.tsx时,代码如下:
    import Lottie from "lottie-react";
    import loadingSpinner from "../animations/loading-spinner.json";
    
    若组件层级更深(如src/pages/Home.tsx),路径需调整为../components/animations/loading-spinner.json,确保层级对应无误。
  • 文件放在public目录下:
    public属于静态资源目录,无法通过import导入,需通过静态资源URL加载并解析JSON:
    import { useEffect, useState } from "react";
    import Lottie from "lottie-react";
    
    export default function Loading() {
      const [animationData, setAnimationData] = useState(null);
    
      useEffect(() => {
        fetch(`${process.env.PUBLIC_URL}/animations/loading-spinner.json`)
          .then(res => res.json())
          .then(data => setAnimationData(data));
      }, []);
    
      if (!animationData) return null;
    
      return <Lottie animationData={animationData} />;
    }
    

二、解决TypeScript类型声明问题

报错中的类型声明缺失问题,可通过添加全局类型声明解决:

  • 在项目根目录或src目录下创建typings.d.ts文件,写入:
    declare module "*.json" {
      const value: any;
      export default value;
    }
    
  • 确保tsconfig.json的include字段包含该声明文件,示例配置:
    {
      "include": ["src/**/*", "typings.d.ts"]
    }
    

三、额外排查点

  • 检查文件名拼写(含大小写),Linux/macOS环境下区分文件名大小写,需完全匹配
  • 若使用Create React App,无需额外配置webpack,确认路径和类型声明后重启项目即可
  • VSCode中可尝试重启TypeScript服务(快捷键Ctrl+Shift+P,输入TypeScript: Restart TS Server)

内容的提问来源于stack exchange,提问作者jaay g.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 23:48:14