Next.js中Lottie动画存public文件夹无法运行问题求助
Next.js中Lottie动画路径问题的原因及解决办法
问题原因拆解
1. 放在public文件夹无法运行
Next.js的public是静态资源目录,里面的文件会直接部署到网站根目录,只能通过URL地址访问,不能用import语法导入。你代码里用import lotusCarAnimation from '/static/lotuserro404.json';尝试导入public里的JSON,Webpack会把它当作模块去解析,但public里的文件不属于Webpack的模块打包范围,自然找不到对应资源,导致动画加载失败。
2. 放在src文件夹仅本地可用
src文件夹里的文件属于Webpack的模块打包范围,本地开发时Webpack会正确解析import路径,所以动画能正常运行。但你用了绝对路径/static/...,生产构建时这个路径会被解析为网站根目录下的static文件夹,而不是src里的static目录,导致生产环境找不到文件,动画无法加载。
解决办法
办法一:用public文件夹+URL加载
把JSON动画文件直接放在public根目录(比如public/lotuserro404.json),然后用Lottie的path属性直接指定URL:
import { Box, Button, Typography } from '@material-ui/core'; import Lottie from 'lottie-react'; const ServiceNotFoundState = () => { return ( <Box m={3}> <Box display="flex" alignItems="center" flexDirection="column"> <Box m={2}> {/* 直接用public里的文件URL */} <Lottie path="/lotuserro404.json" loop={false} /> </Box> <Box m={2}> <Typography variant="h3">该服务不存在!</Typography> </Box> <Box m={4}> <Button disableElevation variant="contained"> 返回 </Button> </Box> </Box> </Box> ); }; export default ServiceNotFoundState;
如果需要用animationData属性,也可以通过fetch获取:
import { Box, Button, Typography } from '@material-ui/core'; import Lottie from 'lottie-react'; import { useEffect, useState } from 'react'; const ServiceNotFoundState = () => { const [animationData, setAnimationData] = useState(null); useEffect(() => { fetch('/lotuserro404.json') .then(res => res.json()) .then(data => setAnimationData(data)); }, []); if (!animationData) return null; return ( <Box m={3}> <Box display="flex" alignItems="center" flexDirection="column"> <Box m={2}> <Lottie animationData={animationData} loop={false} /> </Box> <Box m={2}> <Typography variant="h3">该服务不存在!</Typography> </Box> <Box m={4}> <Button disableElevation variant="contained"> 返回 </Button> </Box> </Box> </Box> ); }; export default ServiceNotFoundState;
办法二:用src文件夹+相对路径导入
把JSON动画放在src目录下(比如src/static/lotuserro404.json),然后用相对路径导入,确保Webpack在本地和生产环境都能正确解析:
import { Box, Button, Typography } from '@material-ui/core'; import Lottie from 'lottie-react'; // 根据组件所在位置调整相对路径,比如组件在src/components下就用../static/... import lotusCarAnimation from './static/lotuserro404.json'; const ServiceNotFoundState = () => { return ( <Box m={3}> <Box display="flex" alignItems="center" flexDirection="column"> <Box m={2}> <Lottie animationData={lotusCarAnimation} loop={false} /> </Box> <Box m={2}> <Typography variant="h3">该服务不存在!</Typography> </Box> <Box m={4}> <Button disableElevation variant="contained"> 返回 </Button> </Box> </Box> </Box> ); }; export default ServiceNotFoundState;
内容的提问来源于stack exchange,提问作者Lucas Paulo
相关产品推荐
相关产品推荐

