当我尝试使用Framer Motion对div进行简单动画时,在浏览器中出现以下错误:
/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)```
当我尝试使用Framer Motion对div进行简单动画时,在浏览器中出现以下错误:
/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
文件并运行 npm install
命令,将 Framer motion 版本降级到“4.1.17”,这样就解决了我的问题。
这对我起作用:
import {AnimatePresence, motion} from 'framer-motion/dist/framer-motion'
以下是Framer Discord对该问题的回应:
关于当前版本的create-react-app(CRA)的问题,该问题正在GitHub上跟踪,链接为:https://github.com/formatjs/formatjs/issues/1395。
经过一些测试,似乎问题出在CRA如何处理ESM依赖项,尤其是传递依赖项似乎没有得到正确处理。此外,关于这个问题还有一个未解决的CRA问题https://github.com/facebook/create-react-app/issues/10356。
解决方案:
CRA的下一个版本已经修复了此问题,您可以今天尝试(https://github.com/facebook/create-react-app/discussions/11278),请注意它仍处于alpha测试阶段。
您可以像其他库的许多票证中描述的那样打补丁来解决CRA的问题。
我在使用Storybook时遇到了类似的问题。通过研究Gatsby应用中类似的错误,我找到了线索:
I was able to fix this by adding gatsby-node.js at the root of my project and the following rule on the webpack:
exports.onCreateWebpackConfig = ({ actions }) => { actions.setWebpackConfig({ module: { rules: [ { test: /\.mjs$/, include: /node_modules/, type: 'javascript/auto', }, ], }, }) }
Storybook使用略有不同的格式进行配置,因此我需要将以下内容添加到.storybook/main.js
中:
module.exports = {
...
webpackFinal: async (config, { configType }) => {
// Resolve error when webpack-ing storybook:
// Can't import the named export 'Children' from non EcmaScript module (only
// default export is available)
config.module.rules.push({
test: /\.mjs$/,
include: /node_modules/,
type: "javascript/auto",
});
return config;
}
}
我想你已经明白了——把上述规则添加到webpack配置中,以便它正确处理*.mjs
文件。
附加信息:
对于那些在应用上述解决方案后仍然遇到“找不到模块'framer-motion / dist / framer-motion'的声明文件”错误的人,取决于您从何处导入功能,以下是使类型正常工作的技巧:
framer-motion.d.ts。
declare module "framer-motion/dist/framer-motion" {
export * from "framer-motion";
}
"framer-motion/dist/framer-motion"
更改为你在应用程序中导入的路径。在我看来,降级到旧版本是最后的手段,因为你将无法使用 Framer Motion 提供的新功能。
在这种情况下应该起作用的是仅稍微更改导入:
import { motion } from 'framer-motion/dist/framer-motion'
使用以下导入解决:
import {motion} from 'framer-motion/dist/es/index'
npm i framer-motion@4.1.17
"dependencies": {
"framer-motion": "^7.2.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "^5.0.1",
},
1.删除node_modules
rm -rf node_modules
2.安装最新版本
npm install react react-dom react-scripts framer-motion
或者
yarn install react react-dom react-scripts framer-motion
3. 导入Framer Motion
import { motion } from "framer-motion";
这对我起作用。
npm uninstall framer-motion
npm install framer-motion@4.1.17