react / react/react-native

Metro babel transformer doesn't recognize .cjs config files (babel.config.cjs, .babelrc.cjs)

未关闭 适合新手
#58,525 4 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

Needs: Author Feedback Needs: Version Info
主要语言
C++
星标
127k
派生
25.3k
平均合并
1 天 23 小时
30 天内合并 PR
4

描述

Description

The @react-native/metro-babel-transformer doesn't recognize .cjs babel config files, which causes silent failures when projects use "type": "module" in their package.json.

Problem

In @react-native/metro-babel-transformer/src/index.js (lines 74-88), the transformer only searches for:

  • .babelrc
  • .babelrc.js
  • babel.config.js

When a project has "type": "module" in package.json:

  • .js files are treated as ES modules by Node.js
  • Babel config files that use module.exports = function(api) {...} (CommonJS) must use the .cjs extension
  • Metro silently falls back to the default preset, ignoring custom plugins

This causes hard-to-debug issues. In my case, the react-native-worklets/plugin wasn't being applied, resulting in runtime errors like "Failed to create a worklet" with no indication that the babel config wasn't being loaded.

Expected behavior

Metro should also search for:

  • .babelrc.cjs
  • babel.config.cjs

This aligns with Babel's own configuration file resolution which supports .cjs extensions.

Workaround

Use extendsBabelConfigPath in Metro config:

// metro.config.cjs

const customConfig = {
  transformer: {
    extendsBabelConfigPath: path.resolve(__dirname, 'babel.config.cjs'),
  },
};

Environment

React Native: 0.81.5
Node.js: 24.x
pnpm monorepo with "type": "module" in package.json

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 packages/react-native-babel-transformer/src/index.js 开始,尤其检查第 74-88 行,并跟踪现有的 Babel 配置查找逻辑。检查 package.json 将 type 设置为 module 的项目的行为,然后验证能够发现 .babelrc.cjs 和 babel.config.cjs,并应用自定义插件,而不是静默回退到 default preset。

由索引模型根据 Issue 内容生成。

评估

技术栈
javascript, node.js, react-native
领域
mobile, tooling
Issue 类型
缺陷
难度
2/5
预计耗时
1-3 小时
活跃度
活跃
描述清晰度
描述清楚
新手友好度
78/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。