Skip to main content

什么是 Codegen?

¥What is Codegen?

Codegen 是一种避免编写大量重复代码的工具。使用 Codegen 不是强制性的:你可以手动编写所有生成的内容。但是,Codegen 生成的脚手架代码可以为你节省大量时间。

¥Codegen is a tool to avoid writing a lot of repetitive code. Using Codegen is not mandatory: you can write all the generated manually. However, Codegen generates scaffolding code that could save you a lot of time.

每次构建 iOS 或 Android 应用时,React Native 都会自动调用 Codegen。有时,你可能希望手动运行 Codegen 脚本以了解实际生成的类型和文件:这是开发 Turbo Native 模块和 Fabric Native 组件时的常见情况。

¥React Native invokes Codegen automatically every time an iOS or Android app is built. Occasionally, you would like to manually run the Codegen scripts to know which types and files are actually generated: this is a common scenario when developing Turbo Native Modules and Fabric Native Components.

Codegen 如何工作

¥How does Codegen works

Codegen 是一个与 React Native 应用紧密耦合的过程。Codegen 脚本位于 react-native NPM 包中,应用在构建时调用这些脚本。

¥Codegen is a process that is tightly coupled with a React Native app. The Codegen scripts live inside the react-native NPM package and the apps call those scripts at build time.

Codegen 会抓取你项目中的文件夹,从你在 package.json 中指定的目录开始,查找一些包含自定义模块和组件的规范(或规范)的特定 JS 文件。Spec 文件是用类型化方言编写的 JS 文件:React Native 目前支持 Flow 和 TypeScript。

¥Codegen crawls the folders in your project, starting from a directory you specify in your package.json, looking for some specific JS files that contains the specification (or specs) for your custom modules and components. Spec files are JS files written in a typed dialect: React Native currently supports Flow and TypeScript.

每次 Codegen 找到一个规范文件时,它都会生成与其关联的样板代码。Codegen 生成一些 C++ 粘合代码,然后生成特定于平台的代码,Android 使用 Java,iOS 使用 Objective-C++。

¥Every time Codegen finds a spec file, it generates the boilerplate code associated to it. Codegen generates some C++ glue-code and then it generates platform-specific code, using Java for Android and Objective-C++ for iOS.