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.