capacitor-plugin-development
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCapacitor Plugin Development
Capacitor 插件开发
Create and maintain Capacitor plugins — scaffolding, native API bridging (iOS/Android), type definitions, testing, and publishing.
创建并维护Capacitor插件 —— 脚手架搭建、原生API桥接(iOS/Android)、类型定义、测试与发布。
Prerequisites
前置要求
| Requirement | Version |
|---|---|
| Node.js | LTS (18+) |
| npm | 6+ |
| Xcode | 15+ (for iOS) |
| Android Studio | Hedgehog 2023.1.1+ (for Android) |
| Capacitor | 6+ |
| 要求 | 版本 |
|---|---|
| Node.js | LTS (18+) |
| npm | 6+ |
| Xcode | 15+(用于iOS开发) |
| Android Studio | Hedgehog 2023.1.1+(用于Android开发) |
| Capacitor | 6+ |
Agent Behavior
Agent 行为规范
- Auto-detect before asking. Read , inspect the directory structure, and infer the plugin's current state before prompting the user.
package.json - Guide step-by-step. Walk the user through one phase at a time. Do not present multiple unrelated tasks simultaneously.
- Skip what exists. If the plugin is already scaffolded, skip scaffolding. If the iOS implementation already exists, skip to the next platform.
- Ask which platforms to target. If the user does not specify, implement all three (iOS, Android, Web).
- 先自动检测再询问:在提示用户之前,先读取、检查目录结构并推断插件的当前状态。
package.json - 分步引导:一次引导用户完成一个阶段的任务,不要同时呈现多个无关任务。
- 跳过已完成部分:如果插件已完成脚手架搭建,则跳过该步骤;如果iOS实现已存在,则直接进入下一平台的开发步骤。
- 询问目标平台:如果用户未指定,则默认实现三个平台(iOS、Android、Web)。
Procedures
开发流程
Step 1: Determine the Task
步骤1:确定任务
Ask the user what they want to do. Common tasks:
- Create a new plugin from scratch — proceed to Step 2.
- Add a new method to an existing plugin — skip to Step 5.
- Add a new platform implementation — skip to the relevant platform step (Step 6, 7, or 8).
- Set up plugin configuration — read and apply.
references/plugin-configuration.md - Set up plugin hooks — read (Plugin Hooks section) and apply.
references/testing-and-workflow.md - Publish the plugin — skip to Step 10.
If the user's intent is clear from context, skip this question and proceed directly.
询问用户想要执行的操作,常见任务包括:
- 从头创建新插件 —— 进入步骤2。
- 为现有插件添加新方法 —— 跳至步骤5。
- 添加新平台实现 —— 跳至对应平台的步骤(步骤6、7或8)。
- 配置插件参数 —— 阅读并执行配置。
references/plugin-configuration.md - 设置插件钩子 —— 阅读(插件钩子章节)并执行设置。
references/testing-and-workflow.md - 发布插件 —— 跳至步骤10。
如果从上下文可明确用户意图,则跳过此问题直接执行对应步骤。
Step 2: Scaffold the Plugin
步骤2:搭建插件脚手架
Read and guide the user through generating a new plugin project using the Capacitor plugin generator.
references/scaffolding.mdGather the following from the user (or infer from context):
- Plugin npm package name
- Android package ID
- Plugin class name
- Repository URL
- License
- Description
Run the generator and verify the scaffold with .
npm run verify阅读并引导用户使用Capacitor插件生成器创建新插件项目。
references/scaffolding.md从用户处收集以下信息(或从上下文推断):
- 插件的npm包名称
- Android包ID
- 插件类名称
- 仓库URL
- 许可证
- 描述信息
运行生成器并通过验证脚手架是否正确。
npm run verifyStep 3: Design the TypeScript API
步骤3:设计TypeScript API
Read and guide the user through defining the plugin interface.
references/designing-api.md- Ask the user what methods the plugin should expose and what data each method accepts/returns.
- Define the plugin interface and all supporting types in .
src/definitions.ts - Register the plugin in using
src/index.ts.registerPlugin()
Ensure:
- Every method and property has JSDoc comments with tags.
@since - Options and result types are defined as separate interfaces.
- String union types are used instead of TypeScript enums.
阅读并引导用户定义插件接口。
references/designing-api.md- 询问用户插件需要暴露哪些方法,以及每个方法接收和返回的数据类型。
- 在中定义插件接口及所有配套类型。
src/definitions.ts - 在中使用
src/index.ts注册插件。registerPlugin()
需确保:
- 每个方法和属性都带有包含标签的JSDoc注释。
@since - 选项和结果类型定义为独立接口。
- 使用字符串联合类型替代TypeScript枚举。
Step 4: Implement the Web Layer
步骤4:实现Web层
Read and implement the web layer in .
references/web-guide.mdsrc/web.ts- Extend and implement the plugin interface.
WebPlugin - For methods that use Web APIs, implement the browser-based logic.
- For methods that have no web equivalent, throw .
this.unimplemented() - For methods that require a web API not available in all browsers, check for the API's existence and throw if missing.
this.unavailable()
After implementation, build and verify:
bash
npm run build
npm run verify:web阅读并在中实现Web层。
references/web-guide.mdsrc/web.ts- 继承并实现插件接口。
WebPlugin - 对于使用Web API的方法,实现基于浏览器的逻辑。
- 对于无Web端等效实现的方法,抛出。
this.unimplemented() - 对于需要特定Web API(并非所有浏览器都支持)的方法,检查API是否存在,若缺失则抛出。
this.unavailable()
实现完成后,构建并验证:
bash
npm run build
npm run verify:webStep 5: Define Method Signatures Across Platforms
步骤5:跨平台定义方法签名
Before implementing native code, determine the method types for each plugin method:
| Type | TypeScript | iOS | Android |
|---|---|---|---|
| Returns a value | | | |
| Returns void | | | |
| Callback (repeated) | | | |
Most methods use the "returns a value" type. Use "callback" only for continuous data streams (e.g., geolocation watching).
在实现原生代码前,确定每个插件方法的类型:
| 类型 | TypeScript | iOS | Android |
|---|---|---|---|
| 返回值 | | | |
| 返回空值 | | | |
| 回调(重复调用) | | | |
大多数方法使用“返回值”类型。仅在处理持续数据流(如地理位置监控)时使用“回调”类型。
Step 6: Implement the iOS Plugin
步骤6:实现iOS插件
Read and implement the iOS layer.
references/ios-guide.md- Create or update the implementation class (e.g., ) with the platform logic. Extend
ios/Sources/<ClassName>Plugin/Example.swiftand mark methods withNSObject.@objc - Create or update the plugin class (e.g., ):
ios/Sources/<ClassName>Plugin/ExamplePlugin.swift- Extend and conform to
CAPPlugin.CAPBridgedPlugin - Set ,
identifier, andjsNameproperties.pluginMethods - Implement each method, reading data from
@objc funcand callingCAPPluginCall,resolve(),reject(), orunavailable().unimplemented()
- Extend
- If the plugin requires third-party iOS dependencies, add them to the file.
.podspec - If the plugin requires permissions, implement and
checkPermissions(), and document the requiredrequestPermissions()keys.Info.plist
After implementation, verify:
bash
npm run verify:ios阅读并实现iOS层。
references/ios-guide.md- 创建或更新实现类(例如),编写平台逻辑。继承
ios/Sources/<ClassName>Plugin/Example.swift并为方法添加NSObject标记。@objc - 创建或更新插件类(例如):
ios/Sources/<ClassName>Plugin/ExamplePlugin.swift- 继承并遵循
CAPPlugin协议。CAPBridgedPlugin - 设置、
identifier和jsName属性。pluginMethods - 实现每个方法,从
@objc func读取数据并调用CAPPluginCall、resolve()、reject()或unavailable()。unimplemented()
- 继承
- 如果插件依赖第三方iOS库,将其添加至文件。
.podspec - 如果插件需要权限,实现和
checkPermissions()方法,并记录所需的requestPermissions()键。Info.plist
实现完成后,验证:
bash
npm run verify:iosStep 7: Implement the Android Plugin
步骤7:实现Android插件
Read and implement the Android layer.
references/android-guide.md- Create or update the implementation class (e.g., ) with the platform logic.
android/src/main/java/<package-path>/Example.java - Create or update the plugin class (e.g., ):
android/src/main/java/<package-path>/ExamplePlugin.java- Extend and add
Plugin.@CapacitorPlugin(name = "<JSName>") - Implement each method, reading data from
@PluginMethodand callingPluginCall,resolve(),reject(), orunavailable().unimplemented()
- Extend
- If the plugin requires third-party Android dependencies, add them to .
android/build.gradle - If the plugin requires permissions:
- Define permission aliases in the annotation.
@CapacitorPlugin - Implement and
checkPermissions().requestPermissions() - Document which permissions the app developer must add to .
AndroidManifest.xml
- Define permission aliases in the
After implementation, verify:
bash
npm run verify:android阅读并实现Android层。
references/android-guide.md- 创建或更新实现类(例如),编写平台逻辑。
android/src/main/java/<package-path>/Example.java - 创建或更新插件类(例如):
android/src/main/java/<package-path>/ExamplePlugin.java- 继承并添加
Plugin注解。@CapacitorPlugin(name = "<JSName>") - 实现每个方法,从
@PluginMethod读取数据并调用PluginCall、resolve()、reject()或unavailable()。unimplemented()
- 继承
- 如果插件依赖第三方Android库,将其添加至。
android/build.gradle - 如果插件需要权限:
- 在注解中定义权限别名。
@CapacitorPlugin - 实现和
checkPermissions()方法。requestPermissions() - 记录应用开发者需添加至的权限。
AndroidManifest.xml
- 在
实现完成后,验证:
bash
npm run verify:androidStep 8: Add Events (If Needed)
步骤8:添加事件(如有需要)
If the plugin emits events to JavaScript:
- TypeScript: Add and
addListener()methods to the plugin interface inremoveAllListeners(). Define an event interface for each event type.src/definitions.ts - Web: Call when the event occurs.
this.notifyListeners('eventName', data) - iOS: Call when the event occurs. Register observers in
self.notifyListeners("eventName", data: [...])if listening to system notifications.load() - Android: Call when the event occurs. Override
notifyListeners("eventName", jsObject)or register broadcast receivers as needed.handleOnConfigurationChanged()
Ensure the event name string is identical across all platforms and matches the parameter in .
eventNameaddListener()如果插件需向JavaScript发送事件:
- TypeScript:在的插件接口中添加
src/definitions.ts和addListener()方法。为每个事件类型定义事件接口。removeAllListeners() - Web:事件触发时调用。
this.notifyListeners('eventName', data) - iOS:事件触发时调用。若需监听系统通知,在
self.notifyListeners("eventName", data: [...])中注册观察者。load() - Android:事件触发时调用。根据需要重写
notifyListeners("eventName", jsObject)或注册广播接收器。handleOnConfigurationChanged()
确保所有平台的事件名称字符串完全一致,且与中的参数匹配。
addListener()eventNameStep 9: Generate Documentation and Verify
步骤9:生成文档并验证
- Add JSDoc comments to all methods and interfaces in if not already present.
src/definitions.ts - Generate documentation:
bash
npm run docgen- Run the full verification:
bash
npm run verify- Lint and format:
bash
npm run lint
npm run fmt- 若中的方法和接口未添加JSDoc注释,补充完整。
src/definitions.ts - 生成文档:
bash
npm run docgen- 执行完整验证:
bash
npm run verify- 代码检查与格式化:
bash
npm run lint
npm run fmtStep 10: Publish
步骤10:发布插件
Read and guide the user through the publishing process.
references/publishing.md- Verify fields are correct (name, version, description, files, capacitor).
package.json - Run the pre-publish checklist.
- Publish to npm:
bash
npm publish --access public阅读并引导用户完成发布流程。
references/publishing.md- 验证字段是否正确(名称、版本、描述、文件、capacitor配置)。
package.json - 执行发布前检查清单。
- 发布至npm:
bash
npm publish --access publicError Handling
错误处理
- fails: Ensure Node.js LTS and npm 6+ are installed. Run
npm init @capacitor/plugin@latestandnode -vto check.npm -v - fails with "module not found": Run
npm run verify:iosto install CocoaPods dependencies.cd ios && pod install --repo-update && cd .. - fails with build errors: Open
npm run verify:androidin Android Studio, sync Gradle, and check for missing dependencies or SDK version mismatches.android/ - fails with TypeScript errors: Check
npm run buildfor type mismatches. Ensure the web implementation insrc/definitions.tscorrectly implements the plugin interface.src/web.ts - name mismatch: The first argument to
registerPlugin()inregisterPlugin()must exactly match thesrc/index.tsproperty on iOS and thejsNamevalue on Android. A mismatch causes the plugin to not load.@CapacitorPlugin(name = "...") - iOS: Methods not callable from JavaScript: Ensure all plugin methods are marked with and listed in the
@objcarray ofpluginMethods.CAPBridgedPlugin - Android: Methods not callable from JavaScript: Ensure all plugin methods have the annotation and are
@PluginMethod().public - Events not received in JavaScript: Verify the event name string is identical in the native call and the TypeScript
notifyListeners()definition. VerifyaddListener()is called before the event fires.addListener() - Plugin configuration values not reading: Verify the key names in match the keys in the Capacitor config file under
getConfig().getString("key").plugins.<PluginJSName> - produces empty output: Ensure JSDoc comments are present on the plugin interface methods in
npm run docgen, not on the implementation classes.src/definitions.ts
- 执行失败:确保已安装Node.js LTS和npm 6+版本。运行
npm init @capacitor/plugin@latest和node -v检查版本。npm -v - 提示“module not found”:运行
npm run verify:ios安装CocoaPods依赖。cd ios && pod install --repo-update && cd .. - 出现构建错误:在Android Studio中打开
npm run verify:android目录,同步Gradle并检查是否缺少依赖或SDK版本不匹配。android/ - 出现TypeScript错误:检查
npm run build中的类型不匹配问题。确保src/definitions.ts中的Web实现正确遵循插件接口。src/web.ts - 名称不匹配:
registerPlugin()中src/index.ts的第一个参数必须与iOS的registerPlugin()属性和Android的jsName值完全一致。名称不匹配会导致插件无法加载。@CapacitorPlugin(name = "...") - iOS:方法无法从JavaScript调用:确保所有插件方法都标记了并在
@objc的CAPBridgedPlugin数组中列出。pluginMethods - Android:方法无法从JavaScript调用:确保所有插件方法都带有注解且为
@PluginMethod()修饰。public - JavaScript未接收到事件:验证原生调用中的事件名称与TypeScript
notifyListeners()定义的名称完全一致。确保addListener()在事件触发前已调用。addListener() - 无法读取插件配置值:验证中的键名与Capacitor配置文件中
getConfig().getString("key")下的键名一致。plugins.<PluginJSName> - 生成空输出:确保JSDoc注释添加在
npm run docgen的插件接口方法上,而非实现类中。src/definitions.ts
Related Skills
相关技能
- — Add Swift Package Manager support to a Capacitor plugin.
capacitor-plugin-spm-support - — Upgrade a Capacitor plugin to a newer Capacitor major version.
capacitor-plugin-upgrades - — Install and configure existing Capacitor plugins in an app project.
capacitor-plugins
- —— 为Capacitor插件添加Swift Package Manager支持。
capacitor-plugin-spm-support - —— 将Capacitor插件升级至更新的Capacitor主版本。
capacitor-plugin-upgrades - —— 在应用项目中安装并配置现有Capacitor插件。",
capacitor-plugins