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

导入framer-motion导致React项目出现ReferenceError报错求助

解决framer-motion导入时出现“React is not defined”的错误

问题描述

React项目中使用framer-motion@11.1.3,仅导入库(未实际使用)就触发Uncaught ReferenceError: React is not defined错误,页面直接空白。导入代码为:

import { AnimatePresence, motion } from "framer-motion/dist/framer-motion";

控制台报错堆栈如下:

Uncaught ReferenceError: React is not defined
at framer-motion.js:1:1 at framer-motion.js:1:1
at ./node_modules/framer-motion/dist/framer-motion.js (framer-motion.js:1:1)
at __webpack_require__ (bootstrap:789:1)
at fn (bootstrap:150:1)
at ./src/modules/auth/components/login-form/LoginForm.jsx (LoginForm.css:45:1)
at __webpack_require__ (bootstrap:789:1) at fn (bootstrap:150:1) at ./src/modules/auth/components/login/Login.jsx (LoginForm.jsx:125:1)
 at __webpack_require__ (bootstrap:789:1) at fn (bootstrap:150:1)
at ./src/modules/auth/AuthModule.jsx (index.js:9:1)
at __webpack_require__ (bootstrap:789:1) at fn (bootstrap:150:1)
at ./src/App.js (App.css:45:1) at __webpack_require__ (bootstrap:789:1)
at fn (bootstrap:150:1)
at ./src/index.js (index.css:45:1)
at __webpack_require__ (bootstrap:789:1)
at fn (bootstrap:150:1) at 1 (useAuth.jsx:9:1)
at __webpack_require__ (bootstrap:789:1)
at checkDeferredModules (bootstrap:45:1)
at Array.webpackJsonpCallback [as push] (bootstrap:32:1)
at main.chunk.js:1:69

Chrome、Edge浏览器测试结果一致。

解决方案

1. 修正导入路径

直接从包根目录导入,不要指定dist子路径:

import { AnimatePresence, motion } from "framer-motion";

包的主入口已经配置好正确的模块导出,能自动处理React依赖,避免未定义错误。

2. 清理依赖缓存(若第一步无效)

如果改路径后问题还在,可能是依赖缓存或安装异常:

  • 删除node_modules文件夹和package-lock.json(或yarn.lock)
  • 重新执行npm install或yarn install
  • 重启开发服务器

3. 检查React版本兼容性

framer-motion 11.x要求React 18及以上版本,如果你的项目用的是React 17或更低,要么升级React,要么把framer-motion降级到兼容版本(比如v10)。

4. 手动导入React(临时方案)

如果项目使用的是React 17以下版本,或者Babel/TS配置未开启自动导入React,可在出错的组件顶部手动添加:

import React from 'react';

不过这只是临时 workaround,优先用前面的方案解决根本问题。

内容的提问来源于stack exchange,提问作者Juan Botero

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 18:45:01