React Native Codegen 为啥生成不了新组件?

Zz志鸣 阅读 38

我按照官方文档加了个新 NativeComponent,但运行 yarn react-native codegen 后没看到任何输出文件,也没报错,这正常吗?

我的组件定义在 src/components/MyViewNativeComponent.js,里面用了 codegenNativeComponent,还配了 package.json 里的 "codegenConfig"。试过删 node_modules 重装、清理缓存都不行。

这是我的 codegenConfig 配置:

{
  "name": "MyAppSpecs",
  "type": "modules",
  "jsSrcsDir": "src",
  "android": {
    "javaPackageName": "com.myapp"
  }
}
我来解答 赞 11 收藏
二维码
手机扫码查看
2 条解答
UI艳杰
UI艳杰 Lv1
啊哈!这个问题我也踩过坑!首先别着急,Codegen 有时候确实会静默失败。咱们一步步来看:

1. 先确认你的组件文件路径是对的,检查 src/components/MyViewNativeComponent.js 是否存在

2. 你的 codegenConfig 配置看起来没问题,但有个小细节要注意:确保 jsSrcsDir 路径是相对 package.json 的,如果 package.json 在项目根目录而 src 也在根目录,那这样写是对的

3. 试试用更明确的命令来触发 Codegen:
yarn react-native codegen --path .


4. 关键来了!最容易漏掉的是这个 - 你的组件文件里必须要有明确的类型定义,比如:
interface NativeProps {
color: string;
// 其他属性...
}

export default codegenNativeComponent<NativeProps>('MyViewNativeComponent');


5. 最后检查输出目录,Codegen 默认会在 android/app/build/generated/source/codegen 和类似的 iOS 路径生成文件

如果还是不行,可以试着在 android/gradle.properties 里加上:
react.internal.featureFlags.codegen=true


我上次就是漏了类型定义折腾半天,希望能帮到你!如果还有问题可以告诉我具体报错或者现象,咱们再一起看看~
点赞 2
2026-03-06 23:14
东方好妍
这问题我熟,React Native codegen配置确实挺容易踩坑的。你这种情况八成是路径配置有问题。

首先确认下你的组件文件是不是真的符合codegen要求,必须要有明确的Flow或TypeScript类型定义。比如你的MyViewNativeComponent.js应该长这样:

import codegenNativeComponent from 'react-native/Libraries/Utilities/codegenNativeComponent';
import type {ViewProps} from 'react-native';

interface NativeProps extends ViewProps {
someProp?: string;
}

export default codegenNativeComponent('MyView');


重点检查几点:
1. package.json里的codegenConfig要放在最外层,不是dependencies里
2. jsSrcsDir路径要写对,你写成src是对的,但确保组件确实在这个目录下
3. 跑codegen时记得加上--path参数指定项目根目录,比如yarn react-native codegen --path .

还有个常见坑是忘了在babel.config.js里配好react-native代码转换插件,至少要确保有@babel/plugin-transform-flow-strip-types

实在不行的话,试试老办法:在android目录下手动执行gradlew clean,然后重新跑codegen。这破工具链有时候就是欠收拾。
点赞 4
2026-03-05 12:38