React项目报错:无法从非ES模块导入命名导出'Children'
React项目突发AnimatePresence导入错误的解决办法
问题情况
项目之前正常运行数周,未修改任何代码的情况下突然报错无法启动。已尝试以下操作但问题依旧:
- 删除
package-lock.json和node_modules后重新执行npm install - 移除疑似引发问题的最新安装包
报错信息:
./node_modules/framer-motion/dist/es/components/AnimatePresence/index.mjs Can't import the named export 'Children' from non EcmaScript module (only default export is available)
项目package.json配置:
{ "name": "project-1", "version": "1.1.0", "private": true, "dependencies": { "@emotion/react": "^11.11.1", "@emotion/styled": "^11.11.0", "@material-tailwind/react": "^2.0.1", "@mui/icons-material": "^5.11.16", "@testing-library/jest-dom": "^5.16.5", "@testing-library/react": "^13.4.0", "@testing-library/user-event": "^13.5.0", "@tinymce/tinymce-react": "^4.3.0", "axios": "^1.4.0", "env-cmd": "^10.1.0", "moment": "^2.29.4", "react": "^18.2.0", "react-dom": "^18.2.0", "react-helmet-async": "^1.3.0", "react-markdown": "^8.0.6", "react-router-dom": "^6.6.1", "react-scripts": "^2.1.3", "react-toastify": "^9.1.2", "web-vitals": "^2.1.4" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "build:dev": "env-cmd -f .env react-scripts start", "build:css": "tailwindcss build -i src/assets/tailwind.css -o src/assets/index.css --watch" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "devDependencies": { "tailwindcss": "^3.2.4" } }
问题原因
- 间接引入framer-motion:你的代码未直接使用
AnimatePresence,但依赖(比如@material-tailwind/react)内部引入了framer-motion。新版本framer-motion采用ES模块命名导出语法,而你的react-scripts版本(2.1.3)过老,无法兼容该语法。 - react-scripts版本过低:
react-scripts@2.x基于Webpack 4,对ES模块的解析能力有限,无法处理最新framer-motion的导出方式。
解决办法
办法1:锁定framer-motion兼容版本
通过resolutions字段强制安装适配老版本react-scripts的framer-motion:
- 安装依赖工具:
npm install npm-force-resolutions --save-dev
- 在
package.json中添加:
"resolutions": { "framer-motion": "^6.5.1" }
- 修改
scripts中的预安装命令:
"scripts": { "preinstall": "npx npm-force-resolutions", // 其他脚本保持不变 }
- 重新执行
npm install。
办法2:升级react-scripts到稳定版本
将react-scripts升级到支持React 18的v5.x版本:
- 卸载旧版本:
npm uninstall react-scripts
- 安装最新稳定版:
npm install react-scripts@5.0.1
- 重新执行
npm install后启动项目:
npm start
注意:若之前执行过
eject操作,升级后可能需要调整少量Webpack配置,但多数项目可平滑过渡。
办法3:临时禁用framer-motion相关功能(可选)
如果不需要@material-tailwind/react的动画功能,可替换为不含framer-motion的版本,或手动修改依赖代码(不推荐,维护成本高)。
内容的提问来源于stack exchange,提问作者Nano
相关产品推荐
相关产品推荐

