在 React 中导入 Framer Motion v5 时出错(使用 create-react-app)

Vic*_*cky 36 motion reactjs 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)```
Run Code Online (Sandbox Code Playgroud)

Din*_*han 29

package.json我通过更改文件并运行将 Framer 运动版本降级到“4.1.17” npm install,它对我有用。


小智 20

这对我有用:

import {AnimatePresence, motion} from 'framer-motion/dist/framer-motion'
Run Code Online (Sandbox Code Playgroud)


Cad*_*din 13

以下是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

选项:

  1. 这在 CRA 的下一个版本中已修复/不会中断,您今天可以尝试 ( https://github.com/facebook/create-react-app/discussions/11278 ),但请注意,尽管它仍处于 alpha 阶段。

  2. 您可以修补 CRA 来解决该问题,如其他图书馆的许多票证中所述


lou*_*lyl 6

附加信息:

对于在应用上述解决方案后遇到错误的人来说Could not find a declaration file for module 'framer-motion/dist/framer-motion'.,根据您导入函数的位置,以下是使类型起作用的技巧:

  • 在src中创建一个声明文件,例如framer-motion.d.ts.
  • 在您刚刚创建的声明文件中添加以下代码。
declare module "framer-motion/dist/framer-motion" {
  export * from "framer-motion";
}
Run Code Online (Sandbox Code Playgroud)
  • 将路径更改"framer-motion/dist/framer-motion"为您在APP中导入的路径。
  • 保存 .d.ts 文件,类型就不会再困扰您了。


use*_*265 6

我在 Storybook 中遇到了类似的问题。我通过研究Gatsby 应用程序中的类似错误找到了线索:

\n
\n

我可以通过在项目根目录添加 gatsby-node.js 并在 webpack 上添加以下规则来解决此问题:

\n
exports.onCreateWebpackConfig = ({ actions }) => {\n  actions.setWebpackConfig({\n    module: {\n      rules: [\n        {\n          test: /\\.mjs$/,\n          include: /node_modules/,\n          type: \'javascript/auto\',\n        },\n      ],\n    },\n  })\n}\n
Run Code Online (Sandbox Code Playgroud)\n
\n

Storybook使用稍微不同的配置格式,因此我必须将其添加到.storybook/main.js

\n
module.exports = {\n  ...\n\n  webpackFinal: async (config, { configType }) => {\n    // Resolve error when webpack-ing storybook:\n    // Can\'t import the named export \'Children\' from non EcmaScript module (only\n    // default export is available)\n    config.module.rules.push({\n      test: /\\.mjs$/,\n      include: /node_modules/,\n      type: "javascript/auto",\n    });\n\n    return config;\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

我想你明白 \xe2\x80\x94 将上述规则添加到 webpack 配置中,以便它*.mjs正确处理文件

\n