Capacitor 跨平台插件开发实战
James Park | 2026-09-01T08:58:30 | JavaScript, Frontend
讲解 Capacitor 插件架构、iOS/Android 原生桥接、TypeScript 类型定义以及自定义插件从开发到发布的完整流程。
# Capacitor 跨平台插件开发实战 ## Capacitor 插件架构 Capacitor 插件由三部分组成:Web 层 TypeScript 接口、iOS Swift 实现、Android Kotlin 实现。插件桥接器自动处理跨平台通信。 ## 创建插件项目 ```bash npm init @capacitor/plugin@latest # 插件名: capacitor-biometric-auth # 包名: com.example.biometric ``` ## TypeScript 接口定义 ```typescript // src/definitions.ts export interface BiometricAuthPlugin { isAvailable(): Promise authenticate(options: AuthOptions): Promise setCredentials(options: CredentialOptions): Promise getCredentials(): Promise } export interface AuthOptions { reason: string title?: string subtitle?: string cancelTitle?: string fallbackTitle?: string } export interface AuthResult { success: boolean error?: string } // src/index.ts import { registerPlugin } from '@capacitor/core' import type { BiometricAuthPlugin } from './definitions' const BiometricAuth = registerPlugin('BiometricAuth', { web: () => import('./web').then(m => new m.BiometricAuthWeb()) }) export * from './definitions' export { BiometricAuth } ``` ## iOS 实现 ```swift // ios/Plugin/BiometricAuthPlugin.swift import Capacitor import LocalAuthentication @objc(BiometricAuthPlugin) public class BiometricAuthPlugin: CAPPlugin, CAPBridgedPlugin { @objc func isAvailable(_ call: CAPPluginCall) { let context = LAContext() var error: NSError? let available = context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) var biometryType = "none" if available { switch context.biometryType { case .faceID: biometryType = "faceId" case .touchID: biometryType = "touchId" default: biometryType = "unknown" } } call.resolve(["available": available, "biometryType": biometryType]) } @objc func authenticate(_ call: CAPPluginCall) { let reason = call.getString("reason") ?? "Authenticate" let context = LAContext() context.localizedCancelTitle = call.getString("cancelTitle") context.localizedFallbackTitle = call.getString("fallbackTitle") context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { success, error in if success { call.resolve(["success": true]) } else { call.resolve(["success": false, "error": error?.localizedDescription ?? "Unknown error"]) } } } } ``` ## Android 实现 ```kotlin // android/src/main/java/BiometricAuthPlugin.kt @CapacitorPlugin(name = "BiometricAuth") class BiometricAuthPlugin : Plugin() { @PluginMethod fun isAvailable(call: PluginCall) { val manager = BiometricManager.from(context) val available = manager.canAuthenticate( BiometricManager.Authenticators.BIOMETRIC_STRONG ) == BiometricManager.BIOMETRIC_SUCCESS val ret = JSObject() ret.put("available", available) ret.put("biometryType", if (available) "biometric" else "none") call.resolve(ret) } @PluginMethod fun authenticate(call: PluginCall) { val reason = call.getString("reason") ?: "Authenticate" val promptInfo = BiometricPrompt.PromptInfo.Builder() .setTitle(call.getString("title") ?: "Authentication") .setSubtitle(reason) .setNegativeBtnText(call.getString("cancelTitle") ?: "Cancel") .build() // ... BiometricPrompt callback implementation } } ``` 开发完成后通过 `npm publish` 发布到 npm 即可,社区中已有大量开源 Capacitor 插件可以参考学习。