Capacitor Expert
Comprehensive reference for building cross-platform apps with Capacitor. Covers architecture, CLI, plugins, framework integration, best practices, and Capawesome Cloud.
Core Concepts
Capacitor is a cross-platform native runtime for building web apps that run natively on iOS, Android, and the web. The web app runs in a native WebView, and Capacitor provides a bridge to native APIs via plugins.
Architecture
A Capacitor app has three layers:
- 1. Web layer -- HTML/CSS/JS app running inside a native WebView (WKWebView on iOS, Android System WebView on Android).
- Native bridge -- Serializes JS plugin calls, routes them to native code, and returns results as Promises.
- Native layer -- Swift/ObjC (iOS) and Kotlin/Java (Android) code implementing native functionality.
Data passed across the bridge must be JSON-serializable. Pass files as paths, not base64.
Project Structure
CODEBLOCK0
The android/ and ios/ directories are full native projects -- they are committed to version control and can be modified directly.
Capacitor Config
INLINECODE2 (preferred) or capacitor.config.json controls app behavior:
CODEBLOCK1
For details, see App Configuration.
Creating a New App
Quick Start
CODEBLOCK2
Web asset directories by framework:
- - Angular:
dist/<project-name>/browser (Angular 17+ with application builder) - React (Vite): INLINECODE5
- Vue (Vite): INLINECODE6
- Vanilla: INLINECODE7
For the full guided creation flow, see capacitor-app-creation.
Capacitor CLI
All commands: npx cap <command>. Most important commands:
| Command | Purpose |
|---|
| INLINECODE9 | Initialize Capacitor in a project |
| INLINECODE10 |
Add Android or iOS platform |
|
npx cap sync | Copy web assets + update native dependencies (run after every plugin install, config change, or web build) |
|
npx cap copy | Copy web assets only (faster, no native dependency update) |
|
npx cap run <platform> | Build, sync, and deploy to device/emulator |
|
npx cap run <platform> -l --external | Run with live reload |
|
npx cap open <platform> | Open native project in IDE |
|
npx cap build <platform> | Build native project |
|
npx cap doctor | Diagnose configuration issues |
|
npx cap ls | List installed plugins |
|
npx cap migrate | Automated upgrade to newer Capacitor version |
For the full CLI reference, see CLI Reference.
Framework Integration
Capacitor works with any web framework. Framework-specific patterns:
Angular
- - Wrap Capacitor plugins in Angular services for DI and testability.
- Plugin event listeners run outside NgZone -- always wrap callbacks in
NgZone.run(). - Register listeners in
ngOnInit, remove in ngOnDestroy.
For details, see capacitor-angular.
React
- - Create custom hooks (
useCamera, useNetwork) that wrap Capacitor plugins. - Use
useEffect for listener registration with cleanup to prevent memory leaks. - React 18 strict mode double-mounts -- ensure cleanup functions work correctly.
For details, see capacitor-react.
Vue
- - Create composables (
useCamera, useNetwork) using Vue 3 Composition API. - Register listeners in
onMounted, remove in onUnmounted. - Vue reactivity picks up
ref changes automatically (no NgZone equivalent needed).
For details, see capacitor-vue.
Plugins
Plugins are Capacitor's extension mechanism. Each plugin exposes a JS API backed by native implementations.
Plugin Sources
- - Official (
@capacitor/*) -- Camera, Filesystem, Geolocation, Preferences, etc. - Capawesome (
@capawesome/*, @capawesome-team/*) -- SQLite, NFC, Biometrics, Live Update, etc. - Community (
@capacitor-community/*) -- AdMob, BLE, SQLite, Stripe, etc. - Firebase (
@capacitor-firebase/*) -- Analytics, Auth, Messaging, Firestore, etc. - MLKit (
@capacitor-mlkit/*) -- Barcode scanning, face detection, translation. - RevenueCat (
@revenuecat/purchases-capacitor) -- In-app purchases.
Installing a Plugin
CODEBLOCK3
After installation, apply any required platform configuration (permissions in AndroidManifest.xml, Info.plist entries, etc.) as documented by the plugin.
Using a Plugin
CODEBLOCK4
For the full plugin index (160+ plugins) and setup guides, see capacitor-plugins.
Plugin Development
Create custom Capacitor plugins with native iOS (Swift) and Android (Java/Kotlin) implementations:
- 1. Scaffold with
npm init @capacitor/plugin@latest. - Define the TypeScript API in
src/definitions.ts. - Implement the web layer in
src/web.ts. - Implement iOS plugin in
ios/Sources/. - Implement Android plugin in
android/src/main/java/. - Verify with
npm run verify.
Key rules:
- - The
registerPlugin() name in src/index.ts must match jsName on iOS and @CapacitorPlugin(name = "...") on Android. - iOS methods need
@objc and must be listed in pluginMethods (CAPBridgedPlugin). - Android methods need
@PluginMethod() annotation and must be public.
For full details, see capacitor-plugin-development.
Cross-Platform Best Practices
Platform Detection
CODEBLOCK5
Permissions
Follow the check-then-request pattern:
CODEBLOCK6
Performance
- - Minimize bridge calls -- batch operations instead of many individual calls.
- Use file paths over base64 for binary data.
- Lazy-load plugins with dynamic imports for code splitting.
Error Handling
Always wrap plugin calls in try-catch:
CODEBLOCK7
For full details, see Cross-Platform Best Practices.
Deep Links
Deep links open specific content in the app from external URLs.
- - iOS: Universal Links via
apple-app-site-association hosted at https://<domain>/.well-known/. - Android: App Links via
assetlinks.json hosted at https://<domain>/.well-known/.
Listener Setup
CODEBLOCK8
Platform Configuration
- - iOS: Add
applinks:<domain> to Associated Domains capability in ios/App/App/App.entitlements. - Android: Add
<intent-filter android:autoVerify="true"> to android/app/src/main/AndroidManifest.xml.
For full setup, see Deep Links.
Storage
| Requirement | Solution |
|---|
| App settings, preferences | INLINECODE62 (native key-value, persists reliably) |
| Sensitive data (tokens, credentials) |
@capawesome-team/capacitor-secure-preferences (Keychain/Keystore) |
| Relational data, offline-first | SQLite (
@capawesome-team/capacitor-sqlite or
@capacitor-community/sqlite) |
| Files, images, documents |
@capacitor/filesystem |
Do NOT use localStorage, IndexedDB, or cookies for persistent data -- the OS can evict them (especially on iOS).
For details, see Storage.
Security
- - Never embed secrets (API keys with write access, OAuth secrets, DB credentials) in client code -- move to a server API.
- Use secure storage (
@capawesome-team/capacitor-secure-preferences) for tokens and credentials, not localStorage or @capacitor/preferences. - HTTPS only -- never allow cleartext HTTP in production.
- Content Security Policy -- add a
<meta> CSP tag in index.html. - Disable WebView debugging in production: set
webContentsDebuggingEnabled: false in capacitor.config.ts. - Prefer Universal/App Links over custom URL schemes (verified via HTTPS).
- iOS Privacy Manifest (
PrivacyInfo.xcprivacy) -- required for iOS 17+ when using privacy-sensitive APIs.
For details, see Security.
Testing
Unit Testing
Mock Capacitor plugins in Jest/Vitest since tests run in Node.js, not a WebView:
CODEBLOCK9
E2E Testing
- - Web E2E: Cypress or Playwright (tests web layer, plugins must be mocked).
- Native E2E: Appium (cross-platform) or Detox (iOS-focused).
Debugging
- - Android: Enable
webContentsDebuggingEnabled: true, open chrome://inspect in Chrome. - iOS: Enable
webContentsDebuggingEnabled: true, use Safari > Develop menu > select device.
For details, see Testing.
Troubleshooting
Android
- -
npx cap sync fails: Verify @capacitor/core and @capacitor/cli versions match. Run cd android && ./gradlew clean. - Build fails after config changes: Clean with
cd android && ./gradlew clean, then rebuild. - Plugin not found at runtime: Run
npx cap sync after plugin installation. Verify Gradle sync completed. - SDK errors: Verify
ANDROID_HOME is set. Install missing SDK versions via Android Studio SDK Manager. - White square notification icon: Push notification icons must be white pixels on transparent background.
iOS
- - Build fails with "no such module": Run
npx cap sync ios. For CocoaPods: cd ios/App && pod install --repo-update. - Build fails after config changes: Clean build folder (Xcode Product > Clean Build Folder) or delete
ios/App/Pods and re-run pod install. - Simulator cannot receive push notifications: Use a physical device for push notification testing.
- Permission denied permanently: Cannot re-request on iOS. Guide user to Settings > App > Permissions.
- WebView not loading: Verify
webDir in capacitor.config.ts matches the actual build output directory.
General
- - Live reload not connecting: Ensure device and dev machine are on the same network. Use
--external flag. - Plugin not found: Run
npx cap sync. Verify plugin is in package.json dependencies. Capacitor is not defined: Install @capacitor/core (npm install @capacitor/core).
For full troubleshooting, see Android Troubleshooting and iOS Troubleshooting.
Upgrading
Capacitor supports upgrades across major versions (4 through 8). Apply each major version jump sequentially -- do not skip intermediate versions.
| Current to Target | Node.js | Xcode | Android Studio |
|---|
| to 5 | 16+ | 14.1+ | Flamingo 2022.2.1+ |
| to 6 |
18+ | 15.0+ | Hedgehog 2023.1.1+ |
| to 7 | 20+ | 16.0+ | Ladybug 2024.2.1+ |
| to 8 | 22+ | 26.0+ | Otter 2025.2.1+ |
Quick automated upgrade:
CODEBLOCK10
If npx cap migrate fails partially, apply manual steps from the upgrade guides.
For app upgrades, see capacitor-app-upgrades.
For plugin upgrades, see capacitor-plugin-upgrades.
Capawesome Cloud
Capawesome Cloud provides cloud infrastructure for Capacitor apps: native builds, live updates, and automated app store publishing.
Website: capawesome.io | Cloud Services: cloud.capawesome.io
Getting Started
CODEBLOCK11
Live Updates
Deploy over-the-air (OTA) web updates to Capacitor apps without going through the app stores. Users receive updates immediately on next app launch.
Setup:
CODEBLOCK12
Configure in capacitor.config.ts:
CODEBLOCK13
Deploy an update:
CODEBLOCK14
Native Builds
Build iOS and Android apps in the cloud without local build environments. Supports signing certificates, environments, and build configuration.
CODEBLOCK15
App Store Publishing
Automate submissions to Apple App Store (TestFlight) and Google Play Store.
CODEBLOCK16
CI/CD Integration
Use token-based auth for CI/CD pipelines:
CODEBLOCK17
For full Capawesome Cloud setup, see capawesome-cloud.
For the Capawesome CLI reference, see capawesome-cli.
Push Notifications
Set up push notifications using Firebase Cloud Messaging (FCM) via @capacitor-firebase/messaging:
CODEBLOCK18
Requires Firebase project setup, platform-specific configuration (APNs for iOS, google-services.json for Android), and permission handling.
For the full setup guide, see capacitor-push-notifications.
In-App Purchases
Set up in-app purchases and subscriptions with either:
- - Capawesome Purchases (
@capawesome-team/capacitor-purchases) -- lightweight, no third-party backend, requires Capawesome Insiders license. - RevenueCat (
@revenuecat/purchases-capacitor) -- full managed backend with receipt validation, analytics, and integrations.
Both require App Store Connect (iOS) and/or Google Play Console (Android) product configuration.
For the full setup guide, see capacitor-in-app-purchases.
Related Skills
Capacitor 专家
使用 Capacitor 构建跨平台应用的全面参考指南。涵盖架构、CLI、插件、框架集成、最佳实践以及 Capawesome Cloud。
核心概念
Capacitor 是一个跨平台原生运行时,用于构建可在 iOS、Android 和 Web 上原生运行的 Web 应用。Web 应用在原生 WebView 中运行,Capacitor 通过插件提供通往原生 API 的桥梁。
架构
一个 Capacitor 应用包含三个层次:
- 1. Web 层 -- 在原生 WebView(iOS 上为 WKWebView,Android 上为 Android System WebView)中运行的 HTML/CSS/JS 应用。
- 原生桥接层 -- 序列化 JS 插件调用,将其路由到原生代码,并以 Promise 形式返回结果。
- 原生层 -- 实现原生功能的 Swift/ObjC(iOS)和 Kotlin/Java(Android)代码。
通过桥接层传递的数据必须是 JSON 可序列化的。使用路径而非 base64 传递文件。
项目结构
my-app/
android/ # 原生 Android 项目(提交到版本控制系统)
ios/ # 原生 iOS 项目(提交到版本控制系统)
App/
App/ # iOS 应用源文件
App.xcodeproj/
src/ # Web 应用源代码
dist/ 或 www/ 或 build/ # 构建后的 Web 资源
capacitor.config.ts # Capacitor 配置
package.json
android/ 和 ios/ 目录是完整的原生项目——它们被提交到版本控制,并且可以直接修改。
Capacitor 配置
capacitor.config.ts(推荐)或 capacitor.config.json 控制应用行为:
typescript
import type { CapacitorConfig } from @capacitor/cli;
const config: CapacitorConfig = {
appId: com.example.app,
appName: My App,
webDir: dist,
server: {
// androidScheme: https, // Cap 6+ 中的默认值
},
};
export default config;
详情请参阅应用配置。
创建新应用
快速开始
bash
1. 创建一个 Web 应用(使用 Vite 的 React 示例)
npm create vite@latest my-app -- --template react-ts
cd my-app && npm install
2. 安装 Capacitor
npm install @capacitor/core
npm install -D @capacitor/cli
3. 初始化 Capacitor
npx cap init My App com.example.myapp --web-dir dist
4. 构建 Web 资源
npm run build
5. 添加平台
npm install @capacitor/android @capacitor/ios
npx cap add android
npx cap add ios
6. 同步并运行
npx cap sync
npx cap run android
npx cap run ios
各框架的 Web 资源目录:
- - Angular:dist/<项目名>/browser(使用 application builder 的 Angular 17+)
- React(Vite):dist
- Vue(Vite):dist
- Vanilla:www
有关完整的引导式创建流程,请参阅 capacitor-app-creation。
Capacitor CLI
所有命令:npx cap 。最重要的命令:
| 命令 | 用途 |
|---|
| npx cap init <name> <id> | 在项目中初始化 Capacitor |
| npx cap add <platform> |
添加 Android 或 iOS 平台 |
| npx cap sync | 复制 Web 资源 + 更新原生依赖(每次安装插件、更改配置或 Web 构建后运行) |
| npx cap copy | 仅复制 Web 资源(更快,不更新原生依赖) |
| npx cap run | 构建、同步并部署到设备/模拟器 |
| npx cap run -l --external | 使用热重载运行 |
| npx cap open | 在 IDE 中打开原生项目 |
| npx cap build | 构建原生项目 |
| npx cap doctor | 诊断配置问题 |
| npx cap ls | 列出已安装的插件 |
| npx cap migrate | 自动升级到更新的 Capacitor 版本 |
有关完整的 CLI 参考,请参阅 CLI 参考。
框架集成
Capacitor 可与任何 Web 框架配合使用。特定于框架的模式:
Angular
- - 将 Capacitor 插件封装在 Angular 服务中,以实现依赖注入和可测试性。
- 插件事件监听器在 NgZone 外部运行——始终在 NgZone.run() 中包装回调。
- 在 ngOnInit 中注册监听器,在 ngOnDestroy 中移除。
详情请参阅 capacitor-angular。
React
- - 创建封装 Capacitor 插件的自定义 Hook(useCamera、useNetwork)。
- 使用 useEffect 进行监听器注册,并附带清理以防止内存泄漏。
- React 18 严格模式会双重挂载——确保清理函数正常工作。
详情请参阅 capacitor-react。
Vue
- - 使用 Vue 3 Composition API 创建可组合函数(useCamera、useNetwork)。
- 在 onMounted 中注册监听器,在 onUnmounted 中移除。
- Vue 的响应式系统会自动捕获 ref 的变化(无需 NgZone 等效项)。
详情请参阅 capacitor-vue。
插件
插件是 Capacitor 的扩展机制。每个插件都公开一个由原生实现支持的 JS API。
插件来源
- - 官方(@capacitor/)-- 相机、文件系统、地理定位、偏好设置等。
- Capawesome(@capawesome/、@capawesome-team/)-- SQLite、NFC、生物识别、实时更新等。
- 社区(@capacitor-community/)-- AdMob、BLE、SQLite、Stripe 等。
- Firebase(@capacitor-firebase/)-- 分析、身份验证、消息传递、Firestore 等。
- MLKit(@capacitor-mlkit/)-- 条码扫描、人脸检测、翻译。
- RevenueCat(@revenuecat/purchases-capacitor)-- 应用内购买。
安装插件
bash
npm install @capacitor/camera
npx cap sync
安装后,根据插件文档应用任何所需的平台配置(AndroidManifest.xml 中的权限、Info.plist 条目等)。
使用插件
typescript
import { Camera, CameraResultType } from @capacitor/camera;
const photo = await Camera.getPhoto({
quality: 90,
resultType: CameraResultType.Uri,
});
有关完整的插件索引(160+ 插件)和设置指南,请参阅 capacitor-plugins。
插件开发
创建具有原生 iOS(Swift)和 Android(Java/Kotlin)实现的自定义 Capacitor 插件:
- 1. 使用 npm init @capacitor/plugin@latest 搭建脚手架。
- 在 src/definitions.ts 中定义 TypeScript API。
- 在 src/web.ts 中实现 Web 层。
- 在 ios/Sources/ 中实现 iOS 插件。
- 在 android/src/main/java/ 中实现 Android 插件。
- 使用 npm run verify 进行验证。
关键规则:
- - src/index.ts 中的 registerPlugin() 名称必须与 iOS 上的 jsName 和 Android 上的 @CapacitorPlugin(name = ...) 匹配。
- iOS 方法需要 @objc,并且必须在 pluginMethods(CAPBridgedPlugin)中列出。
- Android 方法需要 @PluginMethod() 注解,并且必须是 public。
有关完整详情,请参阅 [capacitor-plugin-development