我有一个 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/