reactjs - 如何设置 jest 在 create-react-app 项目中使用自定义 babel 插件?

标签 reactjs jestjs babeljs create-react-app customize-cra

我有一个 CRA 项目,我使用 react-intl 包及其 babel-plugin-formatjs (自动生成用于翻译的消息 ID)。

我围绕 babel-plugin-formatjs 创建了包装器,它获取有关项目的一些附加信息和

为了在 CRA 中使用自定义 babel 插件,我使用 customize-cra 包,并在根文件夹中添加 config-overrides.js 文件,如下所示:

const { override, addBabelPlugin } = require('customize-cra');

function getMyCustomBabelPlugin() {
  // extract some info and return the plugin config:
  return ['babel-plugin-formatjs', { ... // some custom config }]
}

module.exports = {
  webpack: override(
    ... // some overrides,
    addBabelPlugin(getMyCustomBabelPlugin()),
  ),
}

因此,每当我运行 build 命令时,babel 都会运行 babel-plugin-formatjs (并将 id 添加到字符串中进行翻译)。

但是每当我想运行 CRA test 命令时,jest 就不会获取 babel 配置。 我的一些测试渲染使用react-intl的组件,我收到错误:[@formatjs/intl]必须提供id才能格式化消息。因为我的自定义插件不运行。

我看到 CRA 在后台使用默认配置运行 createJestConfig()。 我怎样才能让 Jest 使用想要的 babel 插件? 或者,如何在不弹出或忽略 CRA 默认 createJestConfig() 的情况下传递 jest 附加插件?

我尝试使用自定义 babel 插件在根文件夹中创建一个 babel.config.js 文件,但 jest 没有选择该文件。 还看到了这个答案https://stackoverflow.com/a/62861130/8252705 但想知道它是否可能已经改变,因为它是一个旧答案。

最佳答案

我认为这可能对您有帮助 - https://github.com/arackaf/customize-cra/blob/master/api.md#usebabelrc

由于 addBabelPlugin 不会影响测试配置,因此 useBabelRc 选择 babel 配置文件并覆盖默认 CRA 的 babel 配置

关于reactjs - 如何设置 jest 在 create-react-app 项目中使用自定义 babel 插件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75179132/

相关文章:

reactjs - React - 在最短持续时间内显示加载旋转器

javascript - 如何使用 React 测试库测试点击事件的 stopPropagation?

unit-testing - 如何使用 JEST 框架模拟 chrome API?

javascript - Jenkins 与 Jest 的集成

javascript - 如何设置 TypeScript + Babel + Webpack?

javascript - 使用 Gulp 运行 Webpack + Babel,但没有应用任何预设

javascript - 在 SWR 获取请求中使用 Next.js 动态路由查询对象

javascript - 如何根据回调的响应在 componentDidMount 中设置状态

reactjs - React Native 中的 ScrollView RTL

javascript - babel 错误地转译了导出默认函数