Codegen là tool đọc TypeScript/Flow spec rồi sinh code native (C++, Obj-C++, Java/Kotlin) cho TurboModules và Fabric components. Mục đích: đảm bảo type-safety qua boundary JS ↔ native.
Vì sao cần:
- Bridge cũ: JS gọi native chỉ qua "module name + method name + JSON args". Sai tên/sai args → runtime error, không phát hiện compile.
- New Arch dùng JSI sync call → cần biết exact type signature ở compile time để engine generate vtable đúng. Codegen ghi nhận spec một lần, sinh ra glue code khớp tuyệt đối.
Workflow:
1. Author viết spec TypeScript: interface Spec extends TurboModule { add(a: number, b: number): number }.
2. Codegen chạy lúc build (pod install trên iOS, gradle task trên Android) → đọc tất cả Native*.ts trong project + lib.
3. Generate RCTCalculatorSpec.h/.mm, CalculatorSpec.java, CalculatorJSI.h.
4. Native code phải extends generated class → IDE báo lỗi nếu không match signature.
Cấu hình package.json:
"codegenConfig": {
"name": "RNCalculatorSpec",
"type": "modules",
"jsSrcsDir": "./src"
}Ai chịu trách nhiệm chạy Codegen:
- Lib author: ship spec trong package, user install lib → codegen chạy lúc build local.
- App author: viết spec local cho native module riêng → codegen chạy mỗi pod install/Gradle build.
Lợi ích kéo theo: docs auto từ spec, IDE autocomplete đầy đủ JS-side, refactor rename method được TS trace đầu đến cuối.
Codegen is a tool that reads TypeScript/Flow specs and emits native code (C++, Obj-C++, Java/Kotlin) for TurboModules and Fabric components. Purpose: enforce type-safety across the JS ↔ native boundary.
Why it is needed:
- The old bridge sent only "module name + method name + JSON args" from JS — wrong names/args were runtime errors, not compile-time.
- The New Architecture uses synchronous JSI calls — the engine needs exact type signatures at compile time to generate correct vtables. Codegen records the spec once and emits matching glue.
Workflow:
1. The author writes a TypeScript spec: interface Spec extends TurboModule { add(a: number, b: number): number }.
2. Codegen runs during build (pod install on iOS, a Gradle task on Android) → reads all Native*.ts in the project + libs.
3. Generates RCTCalculatorSpec.h/.mm, CalculatorSpec.java, CalculatorJSI.h.
4. Native code must extend the generated class → the IDE errors out if the signature does not match.
package.json config:
"codegenConfig": {
"name": "RNCalculatorSpec",
"type": "modules",
"jsSrcsDir": "./src"
}Who runs Codegen:
- Library authors: ship the spec in the package — when a user installs the library, codegen runs at their local build.
- App authors: write a local spec for in-app native modules — codegen runs on every pod install/Gradle build.
Knock-on benefits: auto-docs from the spec, full JS-side IDE autocomplete, refactor-renames traced end-to-end by TypeScript.